Write a function to find the longest common prefix string amongst an array of strings.
Python
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if "" in strs or len(strs) == 0:
return ""
elif len(strs) == 1:
return strs[0]
else:
result = strs[[len(str(item)) for item in strs].index(min([len(str(item)) for item in strs]))]
while result in strs:
strs.remove(result)
if strs:
for strs_each in strs:
for index in range(min(len(result), len(strs_each))):
if strs_each[index] != result[index]:
result = result[:index]
break
return result
Java(参考九章算法)
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs == null || strs.length == 0){
return "";
}
String result = strs[0];
for(int i = 1; i < strs.length; i++){
int j = 0;
while(j < strs[i].length() && j < result.length() && strs[i].charAt(j) == result.charAt(j)){
j++;
}
if(j == 0){
return "";
}
result = result.substring(0, j);
}
return result;
}
}