Given k strings, find the longest common prefix (LCP).
Example
For strings "ABCD"
, "ABEF"
and "ACEF"
, the LCP is "A"
For strings "ABCDEFG"
, "ABCEFG"
and "ABCEFA"
, the LCP is "ABC"
解法一:
1 class Solution { 2 public: 3 /** 4 * @param strs: A list of strings 5 * @return: The longest common prefix 6 */ 7 int min(int a, int b) { 8 return ((a < b) ? a : b); 9 } 10 11 int calCount(string & a, string & b) { 12 int la = a.size(); 13 int lb = b.size(); 14 int count = 0; 15 16 for (int i = 0; i < la && i < lb; ++i) { 17 if (a[i] == b[i]) { 18 count++; 19 } else { 20 return count; 21 } 22 } 23 } 24 25 string longestCommonPrefix(vector<string> &strs) { 26 int count = INT_MAX; 27 int size = strs.size(); 28 29 if (size == 0) { 30 return ""; 31 } 32 33 for (int i = 0; i < strs.size() - 1; ++i) { 34 count = min(calCount(strs[i], strs[i + 1]), count); 35 } 36 37 return strs[0].substr(0, count); 38 } 39 };
解法二:
1 class Solution { 2 public: 3 /** 4 * @param strs: A list of strings 5 * @return: The longest common prefix 6 */ 7 string longestCommonPrefix(vector<string> &strs) { 8 if (strs.size() == 0) { 9 return ""; 10 } 11 12 string prefix = ""; 13 for (int i = 0; i < strs[0].length(); i++) { 14 for (int j = 1; j < strs.size(); j++) { 15 if (strs[j][i] != strs[0][i]) { 16 return prefix; 17 } 18 } 19 prefix += strs[0][i]; 20 } 21 22 return prefix; 23 } 24 };