Write a function to find the longest common prefix string amongst an array of strings.
首先判断最小长度,然后就是遍历。记得内部循环后置零
public String longestCommonPrefix(String[] strs) {
if (strs.length==0){
return "";
}
if (strs.length==1){
return strs[0];
}
int i=1;
int j=0;
int minlength = Integer.MAX_VALUE;
for (int a=0;a<strs.length;a++){
minlength = minlength>strs[a].length()?strs[a].length():minlength;
}
StringBuilder stringBuilder = new StringBuilder();
while(j<minlength){
while (i<strs.length){
if (strs[i].charAt(j)!=strs[0].charAt(j)){
if (stringBuilder.length()!=0){
return stringBuilder.toString();
}
else{
return "";
}
}
i++;
}
stringBuilder.append(strs[0].charAt(j));
j++;
i=1;
}
return stringBuilder.toString();
}