您的位置:首页 > 其它

LeetCode 14. Longest Common Prefix

2016-04-11 11:57 465 查看
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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: