Wednesday, May 4, 2022

Question 39 : Longest Common Prefix in an array of Strings in java

Given an array of positive integer and given value X, find Contiguous sub array whose sum is equal to X.
For example :

String[] strArr={"java2Tech","javaworld","javabean","javatemp"}; So Longest common prefix in above String array will be “java” as all above string

So Longest common prefix in above String array will be “java” as all above string starts with “java”.
Lets take one more example:

String[] strArr={"sqlblog","sql2world","sqlquery","sqlproc"};
So Longest common prefix in above String array will be “sql” as all above string starts with “sql”.

Algorithm:

  • Find minimum length String.
  • Iterate over array of String and if we find any mismatch with minimum length String, we break the loop and that index will give us longest common prefix of this array of String,

Java Program to find Longest Common Prefix:

Create the main Class called LongestCommonPrefixMain.java.


public class LongestCommonPrefixMain { public static void main(String[] args) { String[] strArr = { "java2Tech", "javaworld", "javabean", "javatemp" }; String longestPrefix = getLongestCommonPrefix(strArr); System.out.println("Longest Prefix : " + longestPrefix); } public static String getLongestCommonPrefix(String[] strArr) { if (strArr.length == 0) return ""; // Find minimum length String String minStr = getMinString(strArr); int minPrefixStrLength = minStr.length(); for (int i = 0; i < strArr.length; i++) { int j; for (j = 0; j < minPrefixStrLength; j++) { if (minStr.charAt(j) != strArr[i].charAt(j)) break; } if (j < minPrefixStrLength) minPrefixStrLength = j; } return minStr.substring(0, minPrefixStrLength); } public static String getMinString(String[] strArr) { String minStr = strArr[0]; for (int i = 1; i < strArr.length; i++) { if (strArr[i].length() < minStr.length()) minStr = strArr[i]; } return minStr; } }


When you run above program, you will get below output:


Longest Prefix : java

Don't miss the next article! 
Be the first to be notified when a new article or Kubernetes experiment is published.                            

 

 Share This

You may also like

Kubernetes Microservices
Python AI/ML
Spring Framework Spring Boot
Core Java Java Coding Question
Maven AWS