首页 > 代码库 > 14. 字符串数组的最长公共前缀 Longest Common Prefix

14. 字符串数组的最长公共前缀 Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.
  1. public class Solution {
  2. public string LongestCommonPrefix(string[] strs) {
  3. StringBuilder result = new StringBuilder();
  4. if (strs != null && strs.Length > 0) {
  5. Array.Sort(strs);
  6. char[] a = strs[0].ToCharArray();
  7. char[] b = strs[strs.Length - 1].ToCharArray();
  8. for (int i = 0; i < a.Length; i++) {
  9. if (b.Length > i && b[i] == a[i]) {
  10. result.Append(b[i]);
  11. } else {
  12. return result.ToString();
  13. }
  14. }
  15. return result.ToString();
  16. } else {
  17. return "";
  18. }
  19. }
  20. }





null


14. 字符串数组的最长公共前缀 Longest Common Prefix