Java program for longest common substring

Java program for longest common substring

Longest common substring is the substring of two or more strings. In this post, we will see Java program for longest common substring between two given strings. This question is asked in some of the Java interviews. It will be difficult to arrive at the logic during an interview. Hence it is better to be prepared with one or more logic for these kind of problems before any interview.

Longest common substring program in Java

Below is a sample output of running the above program.
In the above program, the max variable tracks the maximum length of the common substring and the pos variable tracks the end index(in string s1) of the common substring.

The variable array looks as below for the above given inputs.

longest common substring

From the above image we can understand that the array is used to track the indices at which the character is equal in both the strings. For example array[3][2] says that the character at index 3 in string 1 and the character at index 2 of string 2 are equal. The array is also used to find the maximum length of substring.

Hope you find this post useful. If you know any other method of solving the longest common substring in Java kindly post it in the comments section.

The following two tabs change content below.
Working as a Java developer since 2010. Passionate about programming in Java. I am a part time blogger.

Add Comment

Required fields are marked *. Your email address will not be published.