Longest common contiguous intersection of two strings.


Write Program to find longest common contiguous intersection from 2 lists provided to the function.

Example:
list1: abcrfghwetf
list2: abrfghwwetxyab
Result : rfghw
Possible Solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class ContinousString {
  private static char[] str1 = "abcrfghwetf".toCharArray();
  private static char[] str2 = "abrfghwwetxyab".toCharArray();
  public static void main(String[] args) {
    int max = 0;
    String longestStr = "";
    String longestResults[][] = new String[str1.length + 1][str2.length + 1];
    for (int i = 0; i < str2.length; i++) {
      char str2char = str2[i];
      for (int j = 0; j < str1.length; j++) {
        if (longestResults[j][i] == null) {
          longestResults[j][i] = "";
        }
        if (str2char == str1[j]) {
          longestResults[j + 1][i + 1] = longestResults[j][i] + str2char;
          if (longestResults[j + 1][i + 1].length() > max) {
            max = longestResults[j + 1][i + 1].length();
            longestStr = longestResults[j + 1][i + 1];
          }
        }
      }
    }
    System.out.println(max + " : "+longestStr);
    printArray(longestResults);
  }
  private static void printArray(Object[][] longestResults) {
    for (int i = 0; i < longestResults.length; i++) {
      for (int j = 0; j < longestResults[i].length; j++) {
        System.out.print(longestResults[i][j] + " -- ");
      }
      System.out.println("");
    }
  }
}

0 comments:

Post a Comment