-
Notifications
You must be signed in to change notification settings - Fork 0
/
LongestCommonSubsequence.java
38 lines (33 loc) · 1.19 KB
/
LongestCommonSubsequence.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
package com.smlnskgmail.jaman.codewarsjava.kyu5;
// https://www.codewars.com/kata/52756e5ad454534f220001ef
public class LongestCommonSubsequence {
private final String firstString;
private final String secondString;
public LongestCommonSubsequence(
String firstString,
String secondString
) {
this.firstString = firstString;
this.secondString = secondString;
}
public String solution() {
int m = firstString.length();
int n = secondString.length();
int[][] nums = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
nums[i][j] = nums[i - 1][j - 1]
+ (firstString.charAt(i - 1) == secondString.charAt(j - 1) ? 1 : 0);
nums[i][j] = Math.max(nums[i][j], nums[i - 1][j]);
nums[i][j] = Math.max(nums[i][j], nums[i][j - 1]);
}
}
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= n; i++) {
if (nums[m][i] - nums[m][i - 1] == 1) {
sb.append(secondString.charAt(i - 1));
}
}
return sb.toString();
}
}