From 3a2252620b2a695686c88867acb13cb12e5d2554 Mon Sep 17 00:00:00 2001 From: nhimanshujain Date: Sat, 15 Oct 2022 20:41:00 +0530 Subject: [PATCH] Longest Common Prefix in JAVA --- Longest Common Prefix.java | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Longest Common Prefix.java 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