Write a function to find the longest common prefix string amongst an array of strings.
Compare one by one, get the common prefix.
string longestCommonPrefix(vector<string>& strs) {
if(strs.size() == 0) return "";
if(strs.size() == 1) return strs[0];
string a = strs[0];
string res;
for(int i = 1; i < strs.size(); ++i) {
string tmp = "";
int j = 0;
int k = 0;
while(j < a.size() && k < strs[i].size()) {
if(a[j] == strs[i][k]) {
tmp= tmp + a[j];
j++; k++;
} else break;
}
a = tmp;
res = tmp;
}
return res;
}Second Round:
To simplify this problem, since we are getting the common prefix for all the input strings, we just need to first sort the input string alphabetically and compare the first and the last to check how much they overlap.
string longestCommonPrefix(vector<string>& strs) {
if(strs.size() < 1) return "";
sort(strs.begin(), strs.end());
string front = strs[0];
string end = strs.back();
for(int i = 0; i < front.size() && i < end.size(); ++i) {
if(front[i] != end[i]) break;
}
return front.substr(0, i);
}
本文介绍了两种寻找字符串数组中最长公共前缀的方法:逐一比较法和排序比较法,并提供了详细的算法实现。

被折叠的 条评论
为什么被折叠?



