Skip to content

Commit 70b7a4a

Browse files
committed
solve longes common subsequence
1 parent 2dac4f4 commit 70b7a4a

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
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 = 1; i <= M; i++) {
9+
for (int j = 1; j <= N; j++) {
10+
if (text1.charAt(i - 1) == text2.charAt(j - 1)) {
11+
// 문자가 일치하면 대각선 값 + 1
12+
dp[i][j] = dp[i - 1][j - 1] + 1;
13+
} else {
14+
// 일치하지 않으면 왼쪽 또는 위쪽 값 중 큰 값 선택
15+
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
16+
}
17+
}
18+
}
19+
20+
// 최종 결과
21+
return dp[M][N];
22+
}
23+
}
24+

0 commit comments

Comments
 (0)