https://leetcode.com/problems/longest-common-subsequence
Longest Common Subsequence (LCS, 최장 공통 부분 수열) 문제:
두 개의 문자열이 주어졌을 때, 두 문자열의 공통 부분 수열 중 가장 긴 길이를 구하는 문제
public int longestCommonSubsequence2(String text1, String text2) {
int len1 = text1.length();
int len2 = text2.length();
int[][] dp = new int[len1][len2];
for (int i = 0; i < len1; i++) {
for (int j = 0; j < len2; j++) {
if (i == 0 && j == 0) {
dp[i][j] = text1.charAt(i) == text2.charAt(j)? 1 : 0;
continue;
}
if (i == 0) {
dp[i][j] = text1.charAt(i) == text2.charAt(j)? 1 : dp[i][j-1];
continue;
}
if (j == 0) {
dp[i][j] = text1.charAt(i) == text2.charAt(j)? 1 : dp[i-1][j];
continue;
}
if (text1.charAt(i) == text2.charAt(j)) {
dp[i][j] = dp[i-1][j-1] + 1;
continue;
}
dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
}
}
return dp[len1-1][len2-1];
}
문자열 A, B의 마지막 문자를 비교했을 때
dp[i][j] = dp[i-1][j-1] + 1dp[i][j] = max(dp[i-1][j], dp[i][j-1])차례로 point 시키면서 생각해보면 쉽다.
인덱싱을 1부터 시작하게 만들면(1-based indexing) index가 0인 부분에 대해 생각해줄 필요가 없다.
public int longestCommonSubsequence(String text1, String text2) {
int len1 = text1.length();
int len2 = text2.length();
int[][] dp = new int[len1 + 1][len2 + 1];
for (int i = 1; i <= len1; i++) {
for (int j = 1; j <= len2; j++) {
if (text1.charAt(i - 1) == text2.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[len1][len2];
}