You are on page 1of 2

Longest Common Substring Algorithm O(mn)

public class LCSBS{

public static void main(String[] args)

String str1= "Rohini is a good student and a girl";

String str2="Sohail is a good student and a boy. He is a good student and a girlfriend at Denver";

LCSBS obj=new LCSBS();

System.out.println("LCSBS Length is : "+obj.longestCommonSubstring(str1,str2));

public int longestCommonSubstring(String str1, String str2)

String sequence = null;

if (str1==null || str2==null)

return 0;

int[][] num = new int[str1.length()][str2.length()];

int maxlen = 0;

int lastSubsBegin = 0;

StringBuilder sequenceBuilder = new StringBuilder();

for (int i = 0; i < str1.length(); i++)

for (int j = 0; j < str2.length(); j++)

if (str1.charAt(i) != str2.charAt(j))

num[i][j] = 0;

else

if ((i == 0) || (j == 0))

num[i][j] = 1;

1
Longest Common Substring Algorithm O(mn)

else

num[i][j] = 1 + num[i - 1][j - 1];

if (num[i][j] > maxlen)

maxlen = num[i][j];

int thisSubsBegin = i - num[i][j] + 1;

if (lastSubsBegin == thisSubsBegin)

{//if the current LCS is the same as the last time this block ran

sequenceBuilder.append(str1.charAt(i));

else

//this block resets the string builder if a different LCS is found

lastSubsBegin = thisSubsBegin;

sequenceBuilder.setLength(0); //clear it

sequenceBuilder.append(str1.substring(lastSubsBegin, (i + 1) ));

sequence = sequenceBuilder.toString();

System.out.println("longest common subString is : "+sequence);

return maxlen;

You might also like