Longest Common Prefix
题目:
Write a function to find the longest common prefix string amongst an array of strings.
题意:
找出所有字符串的最长的公共前缀
思路:先找到最短的一个字符串,然后它的长度当作范围,接着判断所有字符串的同一个下标的字符,若全部相等则添加到返回字符串里。
代码:
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.size() == 0){
return "";
}
int min_len = strs[0].size();
for(string &s : strs){
if(s.size() < min_len){
min_len = s.size();
}
}
string ret_str("");
int flag = 0;
for(int i = 0; i < min_len; ++i){
for(int j = 0; j < strs.size()-1; ++j){
if(strs[j][i] != strs[j+1][i]){
return ret_str;
}
}
ret_str += strs[0][i];
}
return ret_str;
}
};
补充:
找出字符串数组中两个字符串的最长公共前缀。利用后缀数组的思想求解。
代码:
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.size() == 0){
return "";
}
if(strs.size() == 1){
return strs[0];
}
sort(strs.begin(), strs.end());
int max = 0;
int max_index = 0;
vector<string>::iterator max_iter = strs.begin();
auto End = strs.end()-1;
for(auto iter = strs.begin(); iter != End; ++iter){
int i = 0,j = 0;
int cnt = 0;
auto niter = iter+1;
while(i < iter->size() && j < niter->size()){
if((*iter)[i] == (*niter)[j]){
cnt++;
i++;
j++;
}else{
break;
}
}
if(cnt > max){
max = cnt;
max_iter = iter;
max_index = i;
}
}
return max_iter->substr(0, max_index);
}
};