#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.size() == 0)
return "";
char c;
for(int i = 0; i < strs[0].length(); ++i){ //length()与size()
c = strs[0][i];
for(int j = 1; j < strs.size(); ++j){ //纵向比较
if(strs[j].length() == i || strs[j][i] != c)
//i已经是第j个字符串的长度或者不相等
return strs[0].substr(0, i); //不包括i,substr()而不是substring()
}
}
return strs[0]; //strs[0]遍历完成
}
};
int main()
{
string s1 = "ABCD";
string s2 = "ABCF";
string s3 = "ABCR";
vector<string> array;
array.push_back(s1);
array.push_back(s2);
array.push_back(s3);
Solution sol;
string answer(sol.longestCommonPrefix(array));
for(int i = 0; i < answer.size(); ++i){
cout << answer[i];}
cout << endl;
return 0;
参考:https://www.jianshu.com/p/63dcc0d7db75