- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLCS.java
More file actions
Latest commit
38 lines (31 loc) · 917 Bytes
/
Copy pathLCS.java
File metadata and controls
38 lines (31 loc) · 917 Bytes
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
importjava.util.*;
importjava.io.*;
publicclassLCS {
publicstaticStrings, t;
publicstaticint[][] dp;
publicstaticStringrecurse(inti, intj) {
if (dp[i][j] == 0)
return"";
if (s.charAt(i-1) == t.charAt(j-1))
returnrecurse(i - 1, j - 1) + s.charAt(i-1);
elseif (dp[i - 1][j] > dp[i][j - 1])
returnrecurse(i - 1, j);
else
returnrecurse(i, j - 1);
}
publicstaticvoidmain(String[] args) throwsIOException {
BufferedReaderbr = newBufferedReader(newInputStreamReader(System.in));
s = br.readLine();
t = br.readLine();
dp = newint[s.length() + 1][t.length() + 1];
for (inti = 1; i <= s.length(); i++) {
for (intj = 1; j <= t.length(); j++) {
if (s.charAt(i-1) == t.charAt(j-1))
dp[i][j] = dp[i - 1][j - 1] + 1;
else
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
System.out.println(recurse(s.length(), t.length()));
}
}