Table of Contents
If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.
In this post, we are going to see longest common prefix in array of Strings.
So lets say you have string array as below:
1 2 3 |
String[] strArr={"java2blog","javaworld","javabean","javatemp"}; |
So Longest common prefix in above String array will be “java” as all above string starts with “java”.
Lets take one more example:
1 2 3 |
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 a main Class called LongestCommonPrefixMain.java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
package org.arpit.java2blog; public class LongestCommonPrefixMain { public static void main(String[] args) { String[] strArr={"java2blog","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; } } |
1 2 3 |
Longest Prefix : java |
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.