题目:
最长的前缀公共子字符串
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string ""
.
Example 1:
Input: ["flower","flow","flight"] Output: "fl"
Example 2:
Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
#C++版本
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string b="";
int i=0,flag=1,j=0;
if(strs.size()==0){
return "";
}
while(flag==1){
for(j=0;j<strs.size();j++){
if(strs[j].size()==0){
return "";
}
if(strs[j][i]==strs[0][i] && i<strs[j].size()){
continue;
}else{
flag=0;
break;
}
}
if(j==strs.size()){
b+=strs[0][i];
}
i++;
}
return b;
}
};
#Python 版本
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
flag=1
i=0
if len(strs)==0:
return ""
while flag==1:
j=0
while(j<len(strs)):
if len(strs[j])==0:
return ""
print(i,j)
if i<len(strs[j]) and strs[j][i]==strs[0][i] :
j+=1
continue
else:
flag=0
break
if j==len(strs):
i+=1
return strs[0][:i]