How do you find longest common substring ?
Problem statement:
Given two strings S1 & S2. Find the longest common substring between S1 & S2.
Given two strings S1 & S2. Find the longest common substring between S1 & S2.
- import java.util.ArrayList;
- import java.util.List;
- public class LongestCommonSubstring {
- public static void main(String[] args) {
- String S1 = "LCLC";
- String S2 = "CLCL";
- //String S3 = "abcdabccab";
- //String S4 = "bcdaccabaabc";
- List<String> com = commonSubstring(S1, S2);
- for (String s: com){
- System.out.println(s);
- }
- }
- public static List<String> commonSubstring(String s1, String s2) {
- Integer match[][] = new Integer[s1.length()][s2.length()];
- int len1 = s1.length();
- int len2 = s2.length();
- int max = Integer.MIN_VALUE; // max length of the string
- ArrayList<String> result = null; // result list
- for (int i = 0; i < len1; i++) { // row iteration
- for (int j = 0; j < len2; j++) { // column iteration
- if (s1.charAt(i) == s2.charAt(j)) {
- if (i == 0 || j == 0)
- match[i][j] = 1;
- else
- match[i][j] = match[i - 1][j - 1] + 1;
- // if you find a longer common substring re-initialize
- // the max count and update the result list
- if (match[i][j] > max) {
- max = match[i][j];
- result = new ArrayList<String>();
- // substring starts at i-max+1 & ends at i
- result.add(s1.substring(i - max + 1, i + 1));
- }
- // else if you find a common substring with the max length,
- // store it in the list
- else if (match[i][j] == max) {
- result.add(s1.substring(i - max + 1, i + 1));
- }
- } else {
- match[i][j] = 0;
- }
- }
- }
- return result;
- }
- }
Output:
LCL
CLC
Comments
Post a Comment