Write a function to find the longest common prefix string amongst an array of strings.
Solution:
Tips:
two-way merge sort
Java Code:
public class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs.length < 1) {
return "";
}
return longestCommonPrefix(strs, 0, strs.length - 1);
}
private String longestCommonPrefix(String[] strs, int begin, int end) {
if (end < begin) {
return "";
}
if (begin == end) {
return strs[begin];
}
int middle = begin + (end - begin) / 2;
String left = longestCommonPrefix(strs, begin, middle);
String right = longestCommonPrefix(strs, middle + 1, end);
int i = 0;
while (i < left.length() && i < right.length()) {
if (left.charAt(i) != right.charAt(i)) {
break;
}
i++;
}
return left.substring(0, i);
}
}