-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathprint_scs.java
52 lines (41 loc) · 1.59 KB
/
print_scs.java
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
public class print_scs {
public String shortestCommonSupersequence(String str1, String str2) {
int[][] dp = new int[str1.length() +1][str2.length()+1];
for(int i = 0; i <= str1.length(); i++) {
for(int j = 0; j <= str2.length(); j++) {
if(i == 0 || j == 0) dp[i][j] = 0;
else if(str1.charAt(i-1) == str2.charAt(j-1)) {
dp[i][j] = 1 + dp[i-1][j-1];
} else {
dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
}
}
}
int i = str1.length();
int j = str2.length();
StringBuffer result = new StringBuffer();
while(i > 0 && j > 0) {
if (str1.charAt(i-1) == str2.charAt(j-1)) {
result.append(str1.charAt(i-1)); // print lcs variation
i--;
j--;
} else if( dp[i-1][j] > dp[i][j-1] ) {
result.append(str1.charAt(i-1)); // lcs variation
i--;
} else {
result.append(str2.charAt(j-1)); // variation
j--;
}
}
// after adding common i.e lcs we are adding rest of them also
while(i > 0) {
result.append(str1.charAt(i-1));
i--;
}
while(j > 0) {
result.append(str2.charAt(j-1));
j--;
}
return result.reverse().toString();
}
}