Problem:
Write a function to find the longest common prefix string amongst an array of strings.
Answer:
算法1:逐个字符比较,时间复杂度为O(N*L),N是字符串个数,L是最长前缀的长度,运行时间3ms。
public class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs==null || strs.length==0) return "";
String res=strs[0];
for(int i=1;i<strs.length;i++){
//commomPre(strs[i],res);
int len = Math.min(strs[i].length(),res.length());
int j=0;
for(;j<len;j++){
if(strs[i].charAt(j)!=res.charAt(j)){
break;
}
}
if(j==0) res="";
else res = res.substring(0,j);
}
return res;
}
}
算法2的时间复杂度是O(N*M),N是字符串个数,M = strs[0]和其他字符串的前缀长度的平均值, 算法2中字符的比较次数要比算法1多。例如以下例子,运行时间2ms
public class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length == 0||strs == null)
return "";
for(int i = 0; i<strs[0].length(); i++){
char x = strs[0].charAt(i);
for(int j = 1; j<strs.length; j++){
if(strs[j].length() == i || strs[j].charAt(i) != x)
return strs[0].substring(0,i);
}
}
return strs[0];
}
}
算法3,运用2分法的思想,运行时间1ms
public class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs == null || strs.length == 0) return "";
int shortest = Integer.MAX_VALUE, answer = 0;
for(String str : strs) shortest = Math.min(shortest, str.length());
int low = 0, high = shortest;
while(low <= high){
int middle = (low + high) / 2;
if(isSubstring(strs, middle)) low = middle + 1;
else high = middle - 1;
}
return strs[0].substring(0, (low + high) / 2);
}
private boolean isSubstring(String[] strs, int length){
String match = strs[0].substring(0, length);
for(String str : strs) if(!str.substring(0, length).equals(match)) return false;
return true;
}
}