public class Solution {
public String longestCommonPrefix(String[] strs) {
int len = strs.length;
if(len == 0){
return "";
}
if(len == 1){
return strs[0];
}
int length = strs[0].length();
char[][] martix = new char[strs.length][];
for(int i = 0 ; i < strs.length ; i++){
martix[i] = strs[i].toCharArray();
if(strs[i].length() < length){
length = strs[i].length();
}
}
int count = 0;
boolean ended = false;
for(int i = 0 ; i < length ; i++){
char pivot = martix[0][i];
for(int j = 1 ; j < strs.length ; j++){
if(pivot != martix[j][i]){
ended = true;
break;
}
}
if(ended){
break;
}else{
count++;
}
}
return strs[0].substring(0, count);
}
}
似乎确实早上状态比较好,出来当长度为0时返回null为错误,改为“”就好了
Longest Common Prefix
最新推荐文章于 2020-07-03 09:58:21 发布