Skip to content

Commit eb1a643

Browse files
author
jinvicky
committed
longest common subsequence solution
1 parent 2ec4863 commit eb1a643

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
public int longestCommonSubsequence(String text1, String text2) {
3+
int m = text1.length();
4+
int n = text2.length();
5+
6+
int[][] dp = new int[m+1][n+1];
7+
8+
for (int i = 0; i < m; i++) {
9+
for (int j = 0; j < n; j++) {
10+
// DP 계산을 +1로 했어야 했는데 이전 케이스를 재사용하는 -1로만 접근해서 범위 에러가 많이 났었다.
11+
if (text1.charAt(i) == text2.charAt(j)) {
12+
dp[i + 1][j + 1] = dp[i][j] + 1;
13+
} else {
14+
dp[i + 1][j + 1] = Math.max(dp[i][j + 1], dp[i + 1][j]);
15+
}
16+
}
17+
}
18+
19+
return dp[m][n];
20+
}
21+
}

0 commit comments

Comments
 (0)