- Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathLongestCommonSubstring.java
More file actions
Latest commit
73 lines (56 loc) · 2.8 KB
/
Copy pathLongestCommonSubstring.java
File metadata and controls
73 lines (56 loc) · 2.8 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//import Java.util.*;
importjava.io.*;
importjava.util.Scanner;
// create LCSExample1 class to find the Longest Common Subsequence
classLCSExample1 {
// create findLengthOfLCS() method that returns the longest common sequences
publicstaticStringfindLengthOfLCS(Stringstr1, Stringstr2, intp, intq) {
// create a matrix which act as a table for LCS
int[][] tableForLCS = newint[p + 1][q + 1];
// fill the table in the bottom up way
for (inti = 0; i <= p; i++) {
for (intj = 0; j <= q; j++) {
if (i == 0 || j == 0)
tableForLCS[i][j] = 0; // Fill each cell corresponding to first row and first column with 0
elseif (str1.charAt(i - 1) == str2.charAt(j - 1))
tableForLCS[i][j] = tableForLCS[i - 1][j - 1] + 1; // add 1 in the cell of the previous row and column and fill the current cell with it
else
tableForLCS[i][j] = Math.max(tableForLCS[i - 1][j], tableForLCS[i][j - 1]); //find the maximum value from the cell of the previous row and current column and the cell of the current row and previous column
}
}
intindex = tableForLCS[p][q];
inttemp = index;
char[] longestCommonSubsequence = newchar[index + 1];
longestCommonSubsequence[index] = '\0';
inti = p, j = q;
Stringlcs ="";
while (i > 0 && j > 0) {
if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
longestCommonSubsequence[index - 1] = str1.charAt(i - 1);
i--;
j--;
index--;
}
elseif (tableForLCS[i - 1][j] > tableForLCS[i][j - 1])
i--;
else
j--;
}
for (intk = 0; k <= temp; k++)
lcs = lcs + longestCommonSubsequence[k];
returnlcs;
}
publicstaticvoidmain(String[] args) {
Stringstr1, str2, LCS;
Scannersc= newScanner(System.in); //System.in is a standard input stream.
System.out.print("Enter first sequence: ");
str1 = sc.nextLine(); //reads string.
System.out.print("Enter second sequence: ");
str2 = sc.nextLine(); //reads string.
intp = str1.length();
intq = str2.length();
LCS = findLengthOfLCS(str1, str2, p, q);
System.out.print("Sequence1: " + str1 + "\nSequence2: " + str2);
System.out.println("\nLCS: "+LCS);
}
}