Write a function to find the longest common prefix string amongst an array of strings.
解题思路:首先从字符串数组中获取长度最小的字符串,然后循环遍历字符串数组,判断数组中的当前的字符串第一次出现最小字符串的位置,如果没有,则缩小最小字符串,如果最小字符串长度=0,则返回为“”。
public static String longestCommonPrefix(String[] strs) {
if (strs.length == 0)
return "";
int minlen = strs[0].length();
int index = 0;
for (int i = 0; i < strs.length; i++) {
if(minlen > strs[i].length()) {
minlen = strs[i].length();
index = i;
}
}
String minStr = strs[index];
for (int i = 0; i < strs.length; i++) {
if(index != i) {
while(strs[i].indexOf(minStr) != 0) {
minStr = minStr.substring(0,minStr.length()-1);
if(minStr.isEmpty()) {
return "";
}
}
}
}
return minStr;
}
public static String longestCommonPrefix3(String[] strs) {
if (strs.length == 0)
return "";
int minlen = strs[0].length();
int index = 0;
for (int i = 0; i < strs.length; i++) {
if(minlen > strs[i].length()) {
minlen = strs[i].length();
index = i;
}
}
String minStr = strs[index];
for (int i = 0; i < minlen; i++) {
char ch = minStr.charAt(i);
for (int j = 0; j < strs.length; j++) {
if(index != j) {
if(i==strs[j].length() || strs[j].charAt(i) != ch) {
return minStr.substring(0,i);
}
}
}
}
return minStr;
}