Leetcode 14. Longest Common Prefix
https://leetcode.com/problems/longest-common-prefix/
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty()) return "";
string ans=strs[0];
for(int i=0;i<strs[0].size();++i)
for(int j=1;j<strs.size();++j){
if(i>=strs[j].size() || strs[j][i]!=ans[i])
return string(ans,0,i);
}
return ans;
}
};
python版本
def func(strs,idx):
if len(strs)==0 or len(strs[0])<=idx: return ''
s=strs[0][idx]
for ss in strs:
if len(ss)<=idx or ss[idx]!=s:
return ''
return s
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
ans=''
for i in range(10000000000000000):
x=func(strs,i)
if x=='':
return ans
ans+=x