题目:Write a function to find the longest common prefix string amongst an array of strings.
For example:
-
{"a","a","b"} should give "" as there is nothing common in all the 3 strings.
-
{"a", "a"} should give "a" as a is longest common prefix in all the strings.
-
{"abca", "abc"} as abc
-
{"ac", "ac", "a", "a"} as a.
string longestCommonPrefix(vector<string>& strs) {
if (strs.empty())
return "";
int s = strs.size();
string first = strs[0];
int j = 0;
int i;
char c;
char m;
string result = "";
while(first[j] != '\0'){
c = first[j];
for(i = 1; i < s; i++){
if(strs[i].size() <= j){
break;
}
m = strs[i][j];
if(m != c && j == 0){
return result;
}
if(m != c)
break;
}
if(i == s){
result = result + c;
}
j++;
}
return result;
大概思路就是把每一个string的每一个字符一个个比较。如果用java写的话会简单一点,java的string有indexof()的函数,可以先找到第一个和第二个string的最长prefix,然后用indexof函数找后面其他string最长与prefix相同的prefix。
public String longestCommonPrefix(String[] strs) { if (strs.length == 0) return ""; String prefix = strs[0]; for (int i = 1; i < strs.length; i++) while (strs[i].indexOf(prefix) != 0) { prefix = prefix.substring(0, prefix.length() - 1); if (prefix.isEmpty()) return ""; } return prefix; }