Write a function to find the longest common prefix string amongst an array of strings.
运行时间 3ms
#include<string>
#include<vector>
#include<iostream>
using namespace std;
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string res="";
int n=strs.size();
if(n==0){return res;}
if(n==1){return strs[0];}
int len_str1=(strs[0]).length();
if(len_str1==0){return res;}
for(int i=0;i<len_str1;++i){
char c=strs[0][i];
for(int j=1;j<n;j++){
if(((strs[j]).length()<i)||strs[j][i]!=c){
return res;
}
}
res.append(string(1,c));
}
return res;
}
};
void main(){
string s1="abcd";
string s2="abef";
vector<string> sv;
sv.push_back(s1);
sv.push_back(s2);
Solution So;
string s=So.longestCommonPrefix(sv);
cout<<s<<endl;
}