반응형
Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

웹풀스택 공부 중

Leetcode Q.1143 [Medium]: LCS 본문

코딩테스트

Leetcode Q.1143 [Medium]: LCS

lukeit 2024. 8. 21. 16:32

Longest Common Subsequence: Top-Down Approach

 

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.
 

 

class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        n = len(text1)
        m = len(text2)

        # Initializing 2D array with zeros
        # The array has length + 1 to accomodate empty strings as substrings
        dp = [[0] * (m + 1) for _ in range(n+1)]

        # looping through each character
        for i in range(1, n+1):
            for j in range(1, m+1):
                # filling in the dp from the bottom up
                if text1[i - 1] == text2[j - 1]:
                    dp[i][j] = dp[i-1][j-1] + 1
                else:
                    # take the maximum of the value from the left or above 
                    dp[i][j] = max(dp[i-1][j], dp[i][j-1])

        # the bottom-right value in dp will contain the length of the longest common subsequence 
        return dp[n][m]

 

- https://www.youtube.com/watch?v=sSno9rV8Rhg

 

이 영상보고 매우 쉽게 이해했다!

 

 

반응형

'코딩테스트' 카테고리의 다른 글

DP: Dynamic Programming 이란?  (0) 2024.08.20
Leetcode Q.1626 [Medium]: Knapsack DP  (0) 2024.08.20
Leetcode Q.200 [Medium]: DFS  (0) 2024.08.20