Write a function to find the longest common prefix string amongst an array of strings.
题意:找到最长公共前缀
代码:compare方法是求两个字符串的最长公共前缀;再用得到的结果和第三个字符串得到它们的公共子串,以此类推。。。
public class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length == 0){
return "";
}
String ret = strs[0];
for(int i = 1;i< strs.length;i++){
if(!strs[i].startsWith(ret)){
ret = compare(ret, strs[i]);
}
}
return ret;
}
public static String compare(String str1,String str2){
int l = 0;
if(str1.length()>str2.length()){
l = str2.length();
}else{
l = str1.length();
}
String res = "";
for(int i=0;i<l;i++){
if(str1.charAt(i)==str2.charAt(i)){
res += str1.charAt(i);
}else{
break;
}
}
return res;
}
}