- Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathLongestCommonSubstring.java
More file actions
Latest commit
58 lines (44 loc) · 1.37 KB
/
Copy pathLongestCommonSubstring.java
File metadata and controls
58 lines (44 loc) · 1.37 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
packagequestions.virendra;
importjava.util.ArrayList;
importjava.util.List;
publicclassLongestCommonSubstring {
publicstaticList<String> commonSubstring(StringS1, StringS2)
{
Integermatch[][] = newInteger[S1.length()][S2.length()];
intlen1 = S1.length();
intlen2 = S2.length();
intmax = Integer.MIN_VALUE; //Maximum length of the string
ArrayList<String> result = null; //Result list
for(inti=0; i<len1; i++)
{
for(intj=0; j<len2; j++)
{
if(S1.charAt(i) == S2.charAt(j))
{
if ( i == 0 || j==0) match[i][j] = 1;
elsematch[i][j] = match[i-1][j-1] + 1;
if(match[i][j] > max) //If you find a longer common substring re-initialize the max count and update the result list.
{
max = match[i][j];
result = newArrayList<String>();
result.add(S1.substring(i-max+1, i+1)); //substring starts at i-max+1 and ends at i
}
elseif(match[i][j] == max) // else if you find a common substring with the max length, store it in the list.
{
result.add(S1.substring(i-max+1, i+1));
}
}
elsematch[i][j] = 0;
}
}
returnresult;
}
publicstaticvoidmain(Stringargs[])
{
List<String> result = commonSubstring("CLCL", "LCLC");
for(Stringstr: result)
{
System.out.println(str);
}
}
}