[M] 1143. Longest Common Subsequence

YJ·2025년 2월 22일

leetcode

목록 보기
6/100

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의 마지막 문자를 비교했을 때

  • 마지막 문자가 같으면 그 문자를 공통 부분 수열(LCS)에 포함시키고
    dp[i][j] = dp[i-1][j-1] + 1
  • 마지막 문자가 다르면 둘 중 하나를 제외한 경우 중 최댓값을 선택한다.
    dp[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]; 
}

(https://leetcode.com/problems/longest-common-subsequence/solutions/351689/java-python-3-two-dp-codes-of-o-mn-o-min-m-n-spaces-w-picture-and-analysis/?envType=study-plan-v2&envId=leetcode-75)

profile
Hello

0개의 댓글