直接法
直接法又分为竖向扫描和横向扫描,以下的这种方式就是竖向扫描
class Solution {
public String longestCommonPrefix(String[] strs) {
StringBuilder commonPrefix = new StringBuilder();
if (strs == null) {
return null;
}
if (strs.length <= 1) {
return strs[0];
}
int len = strs.length;
for (int i = 0; i < strs[0].length(); i++) {
commonPrefix.append(strs[0].charAt(i));
for (int j = 1; j < len; j++) {
if (strs[j].length() < commonPrefix.length() || !strs[j].startsWith(commonPrefix.toString())) {
commonPrefix.deleteCharAt(i);
return commonPrefix.toString();
}
}
}
return commonPrefix.toString();
}
}
分治法
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
} else {
return longestCommonPrefix(strs, 0, strs.length - 1);
}
}
public String longestCommonPrefix(String[] strs, int start, int end) {
if (start == end) {
return strs[start];
} else {
int mid = (end - start) / 2 + start;
String lcpLeft = longestCommonPrefix(strs, start, mid);
String lcpRight = longestCommonPrefix(strs, mid + 1, end);
return commonPrefix(lcpLeft, lcpRight);
}
}
public String commonPrefix(String lcpLeft, String lcpRight) {
int minLength = Math.min(lcpLeft.length(), lcpRight.length());
for (int i = 0; i < minLength; i++) {
if (lcpLeft.charAt(i) != lcpRight.charAt(i)) {
return lcpLeft.substring(0, i);
}
}
return lcpLeft.substring(0, minLength);
}
}
二分查找
显然,最长公共前缀的长度不会超过字符串数组中的最短字符串的长度。用
minLength 表示字符串数组中的最短字符串的长度,则可以在
[0,minLength] 的范围内通过二分查找得到最长公共前缀的长度。每次取查找范围的中间值
mid,判断每个字符串的长度为
mid 的前缀是否相同,如果相同则最长公共前缀的长度一定大于或等于
mid,如果不相同则最长公共前缀的长度一定小于
mid,通过上述方式将查找范围缩小一半,直到得到最长公共前缀的长度。
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
int minLength = Integer.MAX_VALUE;
for (String str : strs) {
minLength = Math.min(minLength, str.length());
}
int low = 0, high = minLength;
while (low < high) {
int mid = (high - low + 1) / 2 + low;
if (isCommonPrefix(strs, mid)) {
low = mid;
} else {
high = mid - 1;
}
}
return strs[0].substring(0, low);
}
public boolean isCommonPrefix(String[] strs, int length) {
String str0 = strs[0].substring(0, length);
int count = strs.length;
for (int i = 1; i < count; i++) {
String str = strs[i];
for (int j = 0; j < length; j++) {
if (str0.charAt(j) != str.charAt(j)) {
return false;
}
}
}
return true;
}
}
标签:return,前缀,strs,mid,int,length,14,leetcode,String
From: https://www.cnblogs.com/jrjewljs/p/17154373.html