参考:《one-day-one-leetcode》
需要求出多个字符串的最长前缀字符串,即求出最小的字符串,然后求出最小字符串的长度和对应的字符串,然后在最短字符串的长度内进行和其他字符串的匹配即可!
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string longestCommonfix(vector<string>& strs){
int i = 0, min_len = strs[i].length();
string min_str = strs[i];
string s = "";
++i;
while (i < strs.size()){
if (min_len > strs[i].length()){
min_len = strs[i].length();
min_str = strs[i];
}
i++;
}
bool flag = false;
int j = 0;
while (j < min_len){
int count_j = 0;
for (int i = 0; i < strs.size(); i++){
if (strs[i][j] == min_str[j]){
count_j++;
}
else{
flag = true;
break;
}
}
if (flag == true) break;
if (count_j == strs.size()) s += min_str[j];
j++;
}
return s;
}
int main(){
string s[] = { "abc", "abcw", "abcab", "abc" };
vector<string> v;
for (int i = 0; i < sizeof(s) / sizeof(s[0]); i++){
v.push_back(s[i]);
}
cout << longestCommonfix(v) << endl;
return 0;
}
运行结果: