Longest Common Substring (Java)

In computer science, the longest common substring problem is to find the longest string that is a substring of two or more strings.


Given two strings a and b, let dp[i][j] be the length of the common substring ending at a[i] and b[j].


The dp table looks like the following given a="abc" and b="abcd".


Java Solution

public static int getLongestCommonSubstring(String a, String b){
	int m = a.length();
	int n = b.length();
	int max = 0;
	int[][] dp = new int[m][n];
	for(int i=0; i<m; i++){
		for(int j=0; j<n; j++){
			if(a.charAt(i) == b.charAt(j)){
				if(i==0 || j==0){
					dp[i][j] = dp[i-1][j-1]+1;
				if(max < dp[i][j])
					max = dp[i][j];
	return max;

This is a similar problem like longest common subsequence. The difference of the solution is that for this problem when a[i]!=b[j], dp[i][j] are all zeros by default. However, in the longest common subsequence problem, dp[i][j] values are carried from the previous values, i.e., dp[i-1][j] and dp[i][j-1].

Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";

  1. Rishabh Dubey on 2016-10-27

    public static int substrLength(String str1, String str2){ //photograph,tomography
    int count=0,mCount= 0;
    for(int i=0;i<str1.length();i++){
    for(int j=0;j<str2.length();j++){
    if(str1.charAt(i)== str2.charAt(j)){
    count =0;
    for(int k=0;(k+i)<str1.length()&&(k+j)mCount)
    mCount =count;
    return mCount;

Leave a comment