# 【算法】LeetCode算法题-Longest Common Prefix

### 02 第一种解法

public static String longestCommonPrefix(String[] strs) {
String result = "";
if (strs.length == 0) {
return "";
}
if (strs.length == 1) {
return strs[0];
}
String first = strs[0];
for (int i=1; i<=first.length(); i++) {
String prefix = first.substring(0, i);
int count = 0;
for (int j=1; j<strs.length; j++) {
if (strs[j].indexOf(prefix) == 0) {
count = count + 1 ;
}
}
if (count != 0 && count == strs.length-1) {
result = prefix;
}
}
return result;
}

### 03 第二种解法

public static String longestCommonPrefix2(String[] strs) {
if (strs.length == 0) {
return "";
}
String first = strs[0];
for (int i=1; i<strs.length; i++) {
while (strs[i].indexOf(first) != 0) {
first = first.substring(0, first.length()-1);
if (first.isEmpty()) {
return "";
}
}
}
return first;
}

### 04 第三种解法

public String longestCommonPrefix3(String[] strs) {
if (strs.length == 0) {
return "";
}
return partOf(strs, 0, strs.length-1);
}

public String partOf(String[] strs, int leftIndex, int rightIndex) {
if (leftIndex == rightIndex) {
return strs[leftIndex];
} else {
int midIndex = (leftIndex + rightIndex)/2;
String leftStr = partOf(strs, leftIndex, midIndex);
String rightStr = partOf(strs, midIndex+1, rightIndex);
return getResult(leftStr, rightStr);
}
}

public String getResult (String leftStr, String rightStr) {
int min = Math.min(leftStr.length(), rightStr.length());
for (int i=0; i<min; i++) {
if (leftStr.charAt(i) != rightStr.charAt(i)) {
return leftStr.substring(0, i);
}
}
return leftStr.substring(0, min);
}

### 05 小结

posted @ 2018-10-19 08:45 小川94 阅读(...) 评论(...) 编辑 收藏