标签:lse solution empty int family Fix common bst 前缀
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
查找一组字符串中的最长前缀。
这道题解起来很简单,方法也很多,记录一下比较容易想到的两种方法
1 public class Solution { 2 public string LongestCommonPrefix(string[] strs) { 3 int length = strs.Length; 4 if (length == 0) return string.Empty; 5 string result = strs[0]; 6 for (int i = 1; i < length; i++) 7 { 8 result = GetPrefix(strs[i], result); 9 if (string.IsNullOrEmpty(result)) break; 10 } 11 return result; 12 } 13 14 private string GetPrefix(string s1, string s2) 15 { 16 StringBuilder prefix = new StringBuilder(); 17 int minLen = Math.Min(s1.Length, s2.Length); 18 for (int i = 0; i < minLen; i++) 19 { 20 if (s1[i].Equals(s2[i])) 21 { 22 prefix.Append(s1[i]); 23 } 24 else 25 { 26 break; 27 } 28 } 29 return prefix.ToString(); 30 } 31 }
1 public class Solution { 2 public string LongestCommonPrefix(string[] strs) { 3 int length = strs.Length; 4 if (length == 0) return string.Empty; 5 for (int i = 0; i < strs[0].Length; i ++) 6 { 7 for (int j = 1; j < length; j ++) 8 { 9 if (i == strs[j].Length || strs[j][i] != strs[0][i]) 10 { 11 return strs[0].Substring(0, i); 12 } 13 } 14 } 15 return strs[0]; 16 } 17 }
这两种方法比较容易想到也好理解。答案中还有一些别出心裁的方法,不多说了。
标签:lse solution empty int family Fix common bst 前缀
原文地址:https://www.cnblogs.com/Luohys/p/10055269.html