[leetcode_2] 1143. Longest Common Subsequence (Medium)

Junyeong park·2022년 12월 15일
post-thumbnail

1143. Longest Common Subsequence

💡문제

두 문자열 text1과 text2가 주어지면 가장 긴 공통 시퀀스의 길이를 반환합니다. 공통 시퀀스가 없으면 0을 반환합니다.

문자열의 후속은 원래 문자열에서 생성된 새로운 문자열로, 일부 문자(없을 수 있음)는 나머지 문자의 상대적 순서를 변경하지 않고 삭제된다.

예를 들어, "ace"는 "abcde"의 연속이다.

두 문자열의 “공통 시퀀스”는 두 문자열 모두에 공통적인 시퀀스입니다.

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

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".

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

📖Testcase1

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

📖Testcase2

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

📖Testcase3

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.

💡접근방법

  1. 문자열인 text1, text2를 .split를 이용하여 한글자 씩 쪼개진 배열로 바꾸어 새로운 변수(T1, T2)를 설정한다
    2.이중포문을 활용하여 T1의 각 인덱스 값과 T2의 인덱스를 비교하여 같은 값만 새로운 배열 answer에 .push 한다
  2. 문제가 원하는 답이 공통되는 갯수, 즉 answer.length를 리턴한다
var longestCommonSubsequence = function(text1, text2) {
    let T1 = text1.split("");
    let T2 = text2.split("");
    let answer = [];
    
    for(i = 0; i < T1.length; i++){
        for(j = 0; j < T2.length; j++){
            if(T1[i] == T2[j]){
                answer.push(T1[i]);
            }
        }
    }
    
    return answer.length;
};

💡후기

난이도가 medium으로 분류된 문제라 겁을 먹었는데 이중 포문을 활용하니 굉장히 쉽게 풀렸다 웬만한 easy 문제보다도 쉬웠던듯.. ➡️ 지레 겁먹지말자 할 수 있다...

profile
신입 개발자를 꿈꾸는 박준영입니다👨🏻‍💻

0개의 댓글