https://leetcode-cn.com/problems/longest-common-prefix/description/
我的解决方案:
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length==0) return "";
String res = "";
for(int i=0;i<strs[0].length();i++) {
for(int j=1;j<strs.length;j++) {
if(strs[j].length()<i+1)
return res;
if(strs[j].charAt(i)!= strs[0].charAt(i))
return res;
}
res+=strs[0].substring(i, i+1);
}
return res;
}
}
解决方案二:参考了耗时最短的代码,使用二分法,并结合Java.lang.String.StartWith方法判断给定字符串是否为另一字符串的前缀
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 middle = (low + high) / 2;
if (isCommonPrefix(strs, middle))
low = middle + 1;
else
high = middle - 1;
}
return strs[0].substring(0, (low + high) / 2);
}
private boolean isCommonPrefix(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;
}
}