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

The prefix starts as the first string, and for each subsequent string the prefix is progressively shortened until that string actually starts with it, together finding the longest common prefix across all strings.

Quick Links to Explore