[PS] Leet | 1143. 가장 긴 공통 배열

2025. 4. 5. 11:49·CS/PS

문제

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.

조건

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

답

DP를 이용합니다.

 

text1의 길이를 i, text2의 길이를 j라고 했을 때, 가장 긴 공통 배열의 길이를 [i, j]라고 합시다.

 

만약 각 문자열에서 한 자 만큼이 추가되었을 때, 그 두 문자가 같다면 그 둘을 짝 지어서 [i+1, j+1] = [i, j] + 1이 됩니다.

 

(공통 배열의 종류가 아닌, 길이를 구하는 것이기 때문에 무조건 이 둘을 짝지어도 문제되지 않습니다)

 

두 문자가 같지 않다면, [i+1, j+1] = max{ [i, j-1], [i-1, j] } 로 계산합니다.

/**
 * @param {string} text1
 * @param {string} text2
 * @return {number}
 */
var longestCommonSubsequence = function(text1, text2) {
    const len1 = text1.length;
    const len2 = text2.length;

    const lst = [];
    let prev = [];

    for (let i=0; i<len2+1; ++i){
        lst.push(0);
        prev.push(0);
    }

    for (let i=1; i<=len1; ++i) {
        for (let j=1; j<=len2; ++j) {
            if (text1[i-1] === text2[j-1]) {
                lst[j] = prev[j-1] + 1; 
            } else {
                lst[j] = Math.max(prev[j], lst[j-1]);
            }
        }
        prev = [...lst];
    }

    return lst[text2.length];
};

text1의 길이를 n, text2의 길이를 m이라 할 때

시간 복잡도 : O(nm)

공간 복잡도 : O(m)

728x90

'CS > PS' 카테고리의 다른 글

[PS] Leet | 133. 그래프 복사  (0) 2025.04.11
[PS] Leet | 213. 빈집 털이 II  (0) 2025.04.10
[PS] Leet | 300. 가장 긴 증가 수열  (0) 2025.04.02
[PS] Leet | 322. 동전 교환  (0) 2025.03.28
[PS] Leet | 11. 가장 큰 컨테이너  (0) 2025.03.24
'CS/PS' 카테고리의 다른 글
  • [PS] Leet | 133. 그래프 복사
  • [PS] Leet | 213. 빈집 털이 II
  • [PS] Leet | 300. 가장 긴 증가 수열
  • [PS] Leet | 322. 동전 교환
Rayi
Rayi
  • Rayi
    아카이브
    Rayi
  • 전체
    오늘
    어제
    • 분류 전체보기 (259)
      • CS (40)
        • ML (3)
        • CV (2)
        • PS (34)
      • Reveiw (17)
        • Paper (17)
        • Github (0)
      • Pytorch (5)
      • Language (58)
        • Python (7)
        • JavaScript (32)
        • TypeScript (16)
        • C++ (3)
      • IDE (12)
      • Git (13)
      • Frontend (31)
        • React (8)
        • SolidJS (20)
        • CSS (9)
      • UI (3)
      • Backend (15)
        • DB (17)
        • Node.js (11)
  • 블로그 메뉴

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

  • 공지사항

  • 인기 글

  • 태그

    deploy
    DB
    UI
    PyTorch
    CV
    js
    python
    Express
    GAN
    Git
    ML
    ts
    ps
    backend
    API
    SOLID
    figma
    react
    html
    CS
    CSS
    vscode
    postgresql
    mongo
    review
    C++
    Three
    nodejs
    PRISMA
    frontend
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
Rayi
[PS] Leet | 1143. 가장 긴 공통 배열
상단으로

티스토리툴바