难度简单2245
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
示例 1:
代码语言:javascript复制输入:strs = ["flower","flow","flight"]
输出:"fl"
示例 2:
代码语言:javascript复制输入:strs = ["dog","racecar","car"]
输出:""
解释:输入不存在公共前缀。
提示:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i]
仅由小写英文字母组成
#include <stdio.h>
#include <iostream>
using namespace std;
#include <vector>
string longestCommonPrefix(vector<string>& strs);
string longestCommonPrefix(vector<string>& strs) {
string ans;
if(strs.empty() )return ans;
int idx=0;
while(1){
if(strs[0].empty())return ans;
char check=strs[0][idx];
int find=1;
for(int i=0;i<strs.size();i ){
if(idx>=strs[i].size()){
find=0;
break;
}
if(strs[i][idx]!=check){
find=0;
break;
}
}
idx ;
if(find==1)ans =check;
else break;
}
return ans;
//return strs[1];
}
int main(void) {
string str[100]={"flower","flow","flight"};
//vector<string> strs{"flower","flow","flight"};
vector<string> strs(str,str 3);
string s=longestCommonPrefix(strs);
cout<<"输出是"<<s<<endl;
return 0;
}