您的位置:首页 > 其它

Longest Common Prefix

2013-10-10 20:29 239 查看
Write a function to find the longest common prefix string amongst an array of strings.

思路:

先求前两个字符串的公共前缀,然后拿这个前缀和其他字符串进行比对。

int min(int a, int b){
if(a < b)
return a;
return b;
}
string longestCommonPrefix(vector<string> &strs) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int n = strs.size();
if(n == 0)
return "";
if(n == 1)
return strs[0];
string s1 = strs[0], s2 = strs[1];
int i = 0, j;
string result = "";
while(s1[i] == s2[i] && i < min(s1.length(), s2.length())){
result += s1[i];
i++;
}
for(j = 2; j < n; j++){
s1 = strs[j];
i = min(s1.length(), i);
while(s1[i-1] != result[i-1] && i>0){
i--;
}
}
result = result.substr(0,i);
return result;
}


另外一种方法是,依次增加result的长度,判断所有的string在这个位是不是相等。虽然复杂度不变,但是代码变得简练很多。

string longestCommonPrefix(vector<string> &strs) {
int n = strs.size();
if(n == 0)
return "";
if(n == 1)
return strs[0];
int i, j;
string result = "";
for(i = 0;;i++){
for(j = 1; j < n; j++){
if(strs[j].length() < i+1 || strs[j][i] != strs[0][i])
break;
}
if(j < n)
break;
result += strs[0][i];
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: