求一个字符串数组中的最长前缀。
JAVA
方法一
直接暴力解决,最差时间复杂度
O(N2)
没想到竟然AC了。。而且效率排名还在一般左右。。。
public class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length == 0){
return "";
}
String result = "";
for(int i = 0; i < strs[0].length(); ++i ){
char c = strs[0].charAt(i);
int j = 1;
while(j < strs.length && i < strs[j].length() && c == strs[j].charAt(i)){
++j;
}
if(j == strs.length){
result += c;
}else{
break;
}
}
return result;
}
}