diff --git a/Longest Common Prefix.java b/Longest Common Prefix.java new file mode 100644 index 0000000..5939a85 --- /dev/null +++ b/Longest Common Prefix.java @@ -0,0 +1,25 @@ +public String longestCommonPrefix(String[] strs) { + if (strs == null || strs.length == 0) return ""; + return longestCommonPrefix(strs, 0 , strs.length - 1); +} + +private String longestCommonPrefix(String[] strs, int l, int r) { + if (l == r) { + return strs[l]; + } + else { + int mid = (l + r)/2; + String lcpLeft = longestCommonPrefix(strs, l , mid); + String lcpRight = longestCommonPrefix(strs, mid + 1,r); + return commonPrefix(lcpLeft, lcpRight); + } +} + +String commonPrefix(String left,String right) { + int min = Math.min(left.length(), right.length()); + for (int i = 0; i < min; i++) { + if ( left.charAt(i) != right.charAt(i) ) + return left.substring(0, i); + } + return left.substring(0, min); +} \ No newline at end of file