Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
思路:
先求前两个字符串的公共前缀,然后拿这个前缀和其他字符串进行比对。
1 int min(int a, int b){ 2 if(a < b) 3 return a; 4 return b; 5 } 6 string longestCommonPrefix(vector<string> &strs) { 7 // Note: The Solution object is instantiated only once and is reused by each test case. 8 int n = strs.size(); 9 if(n == 0) 10 return ""; 11 if(n == 1) 12 return strs[0]; 13 string s1 = strs[0], s2 = strs[1]; 14 int i = 0, j; 15 string result = ""; 16 while(s1[i] == s2[i] && i < min(s1.length(), s2.length())){ 17 result += s1[i]; 18 i++; 19 } 20 for(j = 2; j < n; j++){ 21 s1 = strs[j]; 22 i = min(s1.length(), i); 23 while(s1[i-1] != result[i-1] && i>0){ 24 i--; 25 } 26 } 27 result = result.substr(0,i); 28 return result; 29 }
另外一种方法是,依次增加result的长度,判断所有的string在这个位是不是相等。虽然复杂度不变,但是代码变得简练很多。
1 string longestCommonPrefix(vector<string> &strs) { 2 int n = strs.size(); 3 if(n == 0) 4 return ""; 5 if(n == 1) 6 return strs[0]; 7 int i, j; 8 string result = ""; 9 for(i = 0;;i++){ 10 for(j = 1; j < n; j++){ 11 if(strs[j].length() < i+1 || strs[j][i] != strs[0][i]) 12 break; 13 } 14 if(j < n) 15 break; 16 result += strs[0][i]; 17 } 18 return result; 19 }