编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
示例 1:
输入:strs = [“flower”,“flow”,“flight”]
输出:"fl"
通过分治算法,分解后再合并
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs==null||strs.length==0){
return "";
}
return fen(0,strs.length-1,strs);
}
public String fen(int left,int right,String[] strs){
if(left==right){
return strs[left];
}
int mid = (right-left)/2+left;
String lefts = fen(left,mid,strs);
String rights = fen(mid+1,right,strs);
StringBuilder sb = new StringBuilder();
for(int i=0;i<(lefts.length()<rights.length()?lefts.length():rights.length());i++){
if(lefts.charAt(i)!=rights.charAt(i)){
break;
}
sb.append(lefts.charAt(i));
}
return sb.toString();
}
}