Skip to content

Commit 8373128

Browse files
committed
longest common subsequence solution
1 parent 1c8e5e4 commit 8373128

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

longest-common-subsequence/jinvicky.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,23 @@ public int longestCommonSubsequence(String text1, String text2) {
1818

1919
return dp[m][n];
2020
}
21+
22+
// -1을 참조해 이전 케이스를 재사용하는 경우는 1부터 m,n까지 하면 그렇게 할 수 있다.
23+
public int longestCommonSubsequence2(String text1, String text2) {
24+
int m = text1.length();
25+
int n = text2.length();
26+
int[][] dp = new int[m + 1][n + 1];
27+
28+
for (int i = 1; i <= m; i++) {
29+
for (int j = 1; j <= n; j++) {
30+
if (text1.charAt(i - 1) == text2.charAt(j - 1)) {
31+
dp[i][j] = dp[i - 1][j - 1] + 1; // 문자가 같으면 대각선 값 + 1
32+
} else {
33+
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); // 위 or 왼쪽 중 큰 값
34+
}
35+
}
36+
}
37+
38+
return dp[m][n];
39+
}
2140
}

0 commit comments

Comments
 (0)