Find Longest Common Prefix

This program finds longest common prefix among strings.

Problem Statement

Write a Java program to find longest common prefix among given strings.

Source Code

1 public class LongestCommonPrefix {
2 public static void main(String[] args) {
3 System.out.println("Eduinq Longest Common Prefix");
4 String[] strs={"flower","flow","flight"};
5 String prefix=strs[0];
6 for(int i=1;i<strs.length;i++){
7 while(strs[i].indexOf(prefix)!=0){
8 prefix=prefix.substring(0,prefix.length()-1);
9 }
10 }
11 System.out.println("Longest common prefix: "+prefix);
12 }
13 }

Program Output

Eduinq Longest Common Prefix
Longest common prefix: fl

Explanation

Prefix initialized with first string. - Iteratively reduced until all strings start with prefix. - Together finds longest common prefix. Conclusion: Shows how to find longest common prefix among strings.

Quick Links to Explore