pre
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
int i,j;
string r;
if(strs.size() == 0){
return r;
}
string pre = strs[0];
for(i=1;i<strs.size();i++){
pre = get_two_pre(pre,strs[i]);
if(pre.size() == 0){
return r;
}
}
return pre;
}
string get_two_pre(string &s1,string &s2){
int len = min(s1.size(),s2.size());
int index = 0;
//string r;
while(index < len && s1[index] == s2[index]){
index++;
}
return s1.substr(0,index);
}
};
/*
示例 1:
输入: ["flower","flow","flight"]
输出: "fl"
示例 2:
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-common-prefix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
post
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string get_two_post(string &s1,string &s2) ;
string longestCommonPostfix(vector<string>& strs) {
int i,j;
string r;
if(strs.size() == 0){
return r;
}
string pre = strs[0];
for(i=1;i<strs.size();i++){
pre = get_two_post(pre,strs[i]);
if(pre.size() == 0){
return r;
}
}
return pre;
}
string get_two_post(string &s1,string &s2){
if (s2.size() == 0 || s2[0] == '\0')
{
return s1;
}
int len = min(s1.size(),s2.size());
int index = 0;
//string r;
while(index < len && s1[s1.size() - index - 1] == s2[s2.size() - index - 1]){
index++;
}
return s1.substr(s1.size()-index,index);
}
int main(){
vector<string> strs;
int n,i;
string s;
while (cin>>n)
{
if (n == 0)
{
break;
}
for (i=0;i<n;i++)
{
cin>>s;
strs.push_back(s);
}
cout<<longestCommonPostfix(strs)<<endl;
strs.clear();
}
//strs.push_back("aa");
//strs.push_back("a");
//strs.push_back("0");
//string s = longestCommonPostfix(strs);
//cout<<s;
return 0;
}
/*
样例输入
3
baba
aba
cba
2
aa
cc
2
aa
a
0
样例输出
ba
a
*/