力扣第14题
代码确实写的很垃圾,但是应该话糙理不糙
public class Test05 {
//寻找最长公共前缀
/**
* 输入:strs = ["flower","flow","flight"]
* 输出:"fl"
* 输入:strs = ["dog","racecar","car"]
* 输出:""
* @param strs
* @return
*/
public static String longestCommonPrefix(String[] strs){
//如果数组为空直接返回null
if(strs.length < 1){
return "";
}else if(strs.length == 1){ //如果数组长度为1,直接返回第一个元素
return strs[0];
}
String tmp = getSameFromTwo(strs[0], strs[1]);
for(int i = 2; i < strs.length; i++){
tmp = getSameFromTwo(tmp, strs[i]);
}
return tmp;
}
//从两个字符串中找最长公共前缀
public static String getSameFromTwo(String s1, String s2){
int p1 = 0;
int p2 = 0;
String tmp = "";
if(s1 == "" || s2 == ""){
return tmp;
}
while(s1.charAt(p1)== s2.charAt(p2)){
tmp = tmp + s1.charAt(p1);
p1++;
p2++;
if(p1 == s1.length() || p2== s2.length()){
break;
}
}
return tmp;
}
//测试
public static void main(String[] args) {
String[] strs ={"",""};
String res = Test05.longestCommonPrefix(strs);
System.out.println(res);
}
}
以上代码,在本地eclipse都可以正常输出空,在力扣上却报错,是为什么呢?