1143. Longest Common Subsequence

2024. 11. 16. 18:04·Algorithm/LeetCode

문제

Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.

A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.

  • For example, "ace" is a subsequence of "abcde".

A common subsequence of two strings is a subsequence that is common to both strings.

Example 1:

Input: text1 = "abcde", text2 = "ace"
Output: 3
Explanation: The longest common subsequence is "ace" and its length is 3.

Example 2:

Input: text1 = "abc", text2 = "abc"
Output: 3
Explanation: The longest common subsequence is "abc" and its length is 3.

Example 3:

Input: text1 = "abc", text2 = "def"
Output: 0
Explanation: There is no such common subsequence, so the result is 0.

Constraints:

  • 1 <= text1.length, text2.length <= 1000
  • text1 and text2 consist of only lowercase English characters.

Solution

class Solution {
    public int longestCommonSubsequence(String text1, String text2) {
        // 최장 공통 부분 문자열을 찾아야 한다.
        // "abcde", "ace"

        // dp[i][j]를 text1의 1번째 문자부터 i번째 문자까지와 text2의 1번째 문자부터 j번째 문자까지에서의 최장 공통 부분 수열의 길이
        int m = text1.length();
        int n = text2.length();

        int[][] dp= new int[m+1][n+1];

        for(int i =1;i<=m;i++)
            for(int j =1;j<=n;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][j-1], dp[i-1][j]);
                }
            }

        return dp[m][n];


    }
}

회고

두 문자열의 최장 공통 부분 문자열을 찾는 문제였다. dp[i][j]를 text1의 1번째 문자부터 i번째 문자까지와 text2의 1번째 문자부터 j번째 문자까지의 최장 공통 부분 수열의 길이로 정의하였다.

 

dp 배열은 모든 요소가 기본값인 0으로 초기화되기 때문에, dp[0][0]=0 코드는 실질적으로 의미는 없으나, text1과 text2가 빈 문자열("")일 경우 최장 공통 부분 수열이 빈 문자열임을 명시적으로 보여주기 위해 추가하였다.

 

평소 1차원 배열로 푸는 DP 문제에 익숙했지만, 이번 문제는 2차원 배열을 활용해야 했다. 앞으로는 2차원 DP 배열을 고려한 접근 방식도 염두에 두자.

'Algorithm > LeetCode' 카테고리의 다른 글

213. House Robber II  (0) 2024.11.30
377. Combination Sum IV  (0) 2024.11.17
139. Word Break  (0) 2024.11.11
300. Longest Increasing Subsequence  (0) 2024.11.07
322. Coin Change  (0) 2024.11.04
'Algorithm/LeetCode' 카테고리의 다른 글
  • 213. House Robber II
  • 377. Combination Sum IV
  • 139. Word Break
  • 300. Longest Increasing Subsequence
사랑우주인
사랑우주인
  • 사랑우주인
    lovelyAlien
    사랑우주인
  • 전체
    오늘
    어제
  • 글쓰기
    관리
    • 분류 전체보기 (209)
      • Programming (4)
        • Spring (28)
        • Java (46)
        • JPA (2)
        • 디자인 패턴 (5)
        • 개발&아키텍처 (0)
      • Network (14)
      • OS (19)
      • Database (1)
      • Kubernetes (0)
      • Kafka (2)
      • Algorithm (49)
        • BaekJoon (1)
        • Programmers (19)
        • Algorithm (5)
        • Socar (2)
        • LeetCode (19)
      • Interview (2)
      • Issues (2)
      • DotJoin (1)
      • Git (4)
      • 독서 (3)
      • 끄적끄적 (1)
      • 외부활동 (26)
        • 항해플러스 (2)
        • JSCODE 네트워크 (19)
        • JSCODE 자바 (5)
      • SQL (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • GitHub
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    Generic
    JSCode
    제네릭
    runner 기법
    OS
    Process
    트랜잭션
    추상화 클래스
    Thread
    Climbing Stairs
    fcfs
    minimum number of arrows to burst balloons
    lower bounded wildcards
    rotting oranges
    socar
    운영체제
    @JsonNaming
    wildcards
    BFS
    준영속 엔티티
    @JsonProperty
    AuthenticationSuccessHandler
    디자인 패턴
    clone graph
    pacific atlantic water flow
    Oauth2
    algorithm
    RR
    Reorder List
    LinkedList
  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.1
사랑우주인
1143. Longest Common Subsequence
상단으로

티스토리툴바