From 0e639a52baadde91e6a58a023ff9a24b3ccd5fc1 Mon Sep 17 00:00:00 2001 From: Shivansh2287 <54775060+Shivansh2287@users.noreply.github.com> Date: Mon, 4 Oct 2021 08:30:12 +0530 Subject: [PATCH] Create longestprefix.java --- longestprefix.java | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 longestprefix.java diff --git a/longestprefix.java b/longestprefix.java new file mode 100644 index 0000000..c2b580b --- /dev/null +++ b/longestprefix.java @@ -0,0 +1,45 @@ +package string; +public class longestprefix{ + static String commonPrefixUtil(String str1, String str2) { + String result = ""; + int n1 = str1.length(), n2 = str2.length(); + + // Compare str1 and str2 + for (int i = 0, j = 0; i <= n1 - 1 && j <= n2 - 1; i++, j++) { + if (str1.charAt(i) != str2.charAt(j)) { + break; + } + result += str1.charAt(i); + } + + return (result); + } + +// A Function that returns the longest common prefix +// from the array of strings + static String commonPrefix(String arr[], int n) { + String prefix = arr[0]; + + for (int i = 1; i <= n - 1; i++) { + prefix = commonPrefixUtil(prefix, arr[i]); + } + + return (prefix); + } + +// Driver program to test above function + public static void main(String[] args) { + String arr[] = {"geeksforgeeks", "geeks", + "geek", "geezer"}; + int n = arr.length; + + String ans = commonPrefix(arr, n); + + if (ans.length() > 0) { + System.out.printf("The longest common prefix is - %s", + ans); + } else { + System.out.printf("There is no common prefix"); + } + } +}