编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例 1:
输入: ["flower","flow","flight"]
输出: "fl"
示例 2:
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
说明:
所有输入只包含小写字母 a-z 。
链接:https://leetcode-cn.com/problems/longest-common-prefix
解题思路:https://leetcode-cn.com/problems/longest-common-prefix/solution/zui-chang-gong-gong-qian-zhui-by-leetcode/
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
int minLen = Integer.MAX_VALUE;
for(String str : strs) {
minLen = Math.min(minLen, str.length());
}
int low = 1;
int high = minLen;
while(low <= high) {
int mid = (low + high)/2;
if(!isCommonSubString(strs, mid)) {
high = mid - 1;
}else {
low = mid + 1;
}
}
return strs[0].substring(0, (low + high)/2);
}
public boolean isCommonSubString(String [] strs,int len) {
String str1 = strs[0].substring(0,len);
for(int i=1; i<strs.length; i++) {
if(!strs[i].startsWith(str1)) {
return false;
}
}
return true;
}
}