Write a function to find the longest common prefix string amongst an array of strings.找出所有字符串最长公共前缀
public class Solution { //runtime = 291ms
public String longestCommonPrefix(String[] strs) {
StringBuffer lstring = new StringBuffer();
if (strs.length == 0){
return "";
}
if (strs.length == 1){
return strs[0];
}
int i;
int j;
int len;
int longest = Integer.MAX_VALUE;
for (i = 1; i < strs.length; i ++){
//两个字符串的最长公共前缀不会超过短字符串的长度,先判断一下,节省比较时间
len = Math.min(strs[0].length(), strs[i].length());
j = 0;
while ((j < len)&&(strs[0].charAt(j) == strs[i].charAt(j))){
j ++;
}
longest = Math.min(j, longest);
}
for (i = 0; i < longest; i ++){
lstring.append(strs[0].charAt(i));
}
return lstring.toString();
}
}