题目地址: leetcode.com/problems/lo…
给定一个字符串数组A AA,求其最长公共前缀。
可以采用分治法。先求A[0,...,l A /2]的所有字符串的最长公共前缀,然后再求A[l A /2+1,...,l A −1]的所有字符串的最长公共前缀,然后将两个前缀合起来再求一次最长公共前缀。代码如下:
public class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
return longestCP(strs, 0, strs.length - 1);
}
// 找strs[l,...,r]的最长公共子前缀
private String longestCP(String[] strs, int l, int r) {
if (l == r) {
return strs[l];
}
int mid = l + (r - l >> 1);
String s1 = longestCP(strs, l, mid);
String s2 = longestCP(strs, mid + 1, r);
int minLen = Math.min(s1.length(), s2.length());
StringBuilder sb = new StringBuilder(minLen);
for (int i = 0; i < minLen; i++) {
if (s1.charAt(i) == s2.charAt(i)) {
sb.append(s1.charAt(i));
} else {
break;
}
}
return sb.toString();
}
}
时间复杂度O(nm),m为字符串最长长度。空间O(mlogn)。 相关链接: