Wednesday, November 30, 2011

A program to print the longest common substring of the two given strings (Java)

//This Java program accepts two strings
//from the user and then prints the longest common
//substring of the two given strings.
//SUBSTRING: A substring of a string is a string that can
//be obtained by removing some characters from
//the beginning or the end of the given string. For example
// "uter" is a substring of "computer".
//
//Sample Output of program :-
/*
Enter the two strings :
i like computer
put it down

Longest Common Substring is :-
put
*/

import java.util.*;
class longestCommonSubstring
{
public static void main()
{
    System.out.println("Enter the two strings : ");
    String a,b;
    Scanner sc=new Scanner(System.in);
    a=sc.nextLine();
    b=sc.nextLine();
    int m=a.length();
    int n=b.length();
    int ar[][]=new int[m+1][n+1];
    int i;
    int j;
    for(i=0;i<m+1;i++)   
    for(j=0;j<n+1;j++)
    ar[i][j]=0;
   
   
    int l=0,x=0,y=0;
    for(i=1;i<m+1;i++)
    {
        for(j=1;j<n+1;j++)
        {
            if(a.charAt(i-1)==b.charAt(j-1))
            {
                ar[i][j]=ar[i-1][j-1]+1;
                if(ar[i][j]>=l)
                {
                    l=ar[i][j];  //l holds value of the largest number in the square which
                    x=i;         //is also the length of longest substring.x and y store its
                    y=j;         //co-ordinates.
                }
            }
        }
    }
   
    String lcs="";
    int k=0;
    for(i=l;i>=1;i--)     //Storing the largest common substring
    {
        if(ar[x][y]!=0)
        {
            lcs=a.charAt(x-1)+lcs;
            x--;y--;
        }
    }
    System.out.println("\nLongest Common Substring is :-");
    System.out.println(lcs);          //Printing the largest common substring
}
}

//Author : Mayank Rajoria

No comments:

Post a Comment