question:
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string “”.
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z.
解法一:水平比较一
思路:先求出第一个字符串与第二个字符串的公共子串,再用此公共子串和第三个字符串对比的出公共子串,以此类推。当比较过程中若公共子串变为""(空字符串),则可以返回""(空字符串)。
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length==0){
return "";
}
String pre = strs[0];
for(int i=1;i<strs.length;i++){
//要善于使用API
while(strs[i].indexOf(pre)!=0){
pre = pre.substring(0,pre.length()-1);
if(pre.equals("")){
return "";
}
}
}
return pre;
}
}
解法二:水平比较二
思路:我们可以从下标0开始先比较每一个字符的相同下标的字符,若所有字符串下标处字符均相同,那么下标++。
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) return "";
for (int i = 0; i < strs[0].length() ; i++){
char c = strs[0].charAt(i);
for (int j = 1; j < strs.length; j ++) {
//i之前为已经确认的公共前缀,此时若某一字符串遍历完毕,或者i下标处字符不同则返回即可;
if (i == strs[j].length() || strs[j].charAt(i) != c)
return strs[0].substring(0, i);
}
}
return strs[0];
}
}
解法三:分治
思路:递归分治,直至字符串数组只有一个字符串
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length==0){
return "";
}
return pre(strs,0,strs.length-1);
}
private String pre(String[] strs,int l,int r){
if(l==r){
return strs[l];
}else{
int mid = (l+r)/2;
String ls = pre(strs,l,mid);
String rs = pre(strs,mid+1,r);
int min = Math.min(ls.length(),rs.length());
int i =0;
for(;i<min;i++){
if(ls.charAt(i)!=rs.charAt(i)){
break;
}
}
return ls.substring(0,i);
}
}
}
解法四:二分查找
思路:字符串数组中最短的字符串会限制公共前缀的长度,利用最短字符串的长度对其进行二分比较。注意善于利用API。
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;
}