题目:
编写一个函数来查找字符串数组中的最长公共前缀,如果不存在公共前缀,返回空字符串 ""。
示例:
输入: ["flower","flow","flight"]
输出: "fl"
代码:
public class Test10 {
public static void main(String[] args) {
String[] test = new String[]{"c","c"};
String s = new Test10().longestCommonPrefix(test);
System.out.println(s);
}
public String longestCommonPrefix(String[] strs) {
if (strs.length==0) {
return "";
}
if (strs.length==1) {
return strs[0];
}
int minLength =strs[0].length();
int number =0;
for (String str : strs) {
if (str.length()<minLength) {
minLength = str.length();
}
number++;
}
String result = "";
for (int i = 1; i <= minLength; i++) {
boolean flag =false;
for (int j = 1; j < number; j++) {
if (!strs[0].substring(0,i).equals(strs[j].substring(0,i))) {
flag = true;
break;
}
}
if (flag==false) {
result = strs[0].substring(0,i);
}else{
break;
}
}
return result;
}
}