Skip to content

Commit

Permalink
Longest Common Prefix in JAVA
Browse files Browse the repository at this point in the history
  • Loading branch information
himanshujaindev committed Oct 15, 2022
1 parent 7c9fa3e commit 3a22526
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions Longest Common Prefix.java
Original file line number Diff line number Diff line change
@@ -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);
}

0 comments on commit 3a22526

Please sign in to comment.