最长公共前缀
编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""
。
输入: ["flower","flow","flight"]
输出: "fl"
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
所有输入只包含小写字母 a-z 。
首先选择数组里最小的一个,他可能是公共前缀的最大长度。然后以这个数来进行二分法,当公共值等于mid的时候,有可能相等或者大于;当小于的时候,就mid-1继续判断
class Solution140002{
public String longestCommonPrefix(String[] strs){
if (strs.length == 0 || strs == null){
return "";
}
int minLength = Integer.MAX_VALUE;
for (String str : strs) {
minLength = Math.min(minLength , str.length());
}
int low = 0,high = minLength;
while (low < high){
int mid = low + (high - low + 1) / 2;// 防溢出
if (isCommonPrefix(strs,mid)){
low = mid;//注意是while循环 如果公共值大于mid 则一直判断
}else {
low = mid - 1;
}
}
return strs[0].substring(0,low);
}
private boolean isCommonPrefix(String[] strs, int length) {
String str0 = strs[0].substring(0, length);
int count = strs.length;
for (int i = 1; i < count; i++) {
String str = strs[i];
for (int j = 0; j < length; j++) {
if (str0.charAt(j) != str.charAt(j)){
return false;
}
}
}
return true;
}
}
时间复杂度:O(mn log m) 其中m是字符串的最小长度,n是字符串的数量。二分查找的迭代次数是O(log m) 每次迭代最多需要比较mn个字符。
空间复杂度: O(1) 使用的额外空间复杂度为常数