地址:https://leetcode-cn.com/problems/longest-common-prefix/
思路:遍历判断即可
Code:
#include<iostream>
#include<algorithm>
#include<vector>
#include<cmath>
#include<map>
#include<unordered_map>
#include<cstring>
using namespace std;
typedef long long LL;
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
int n=strs.size();
if(!n) return "";
int len=strs[0].length(),p=1;
for(int i=0;i<n;++i)
len=min(len,int(strs[i].length()));
string res="",str=strs[0];
for(int i=0;i<len;++i)
{
for(int j=0;j<n;++j)
if(strs[j][i]!=str[i]){
p=0; break;
}
if(!p) break;
res+=str[i];
}
return res;
}
};
int main()
{
int n;
string str;
vector<string> iv;
Solution So;
cin>>n;
for(int i=0;i<n;++i)
{
cin>>str;
iv.push_back(str);
}
cout<<So.longestCommonPrefix(iv)<<endl;
return 0;
}