algorithm

1143. Longest Common Subsequence

식피두 2020. 9. 10. 16:38

https://leetcode.com/problems/longest-common-subsequence/

 

Longest Common Subsequence - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

95%!!! 376ms

class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        
        dp = []
        for r in range(len(text1)+1):
            dp.append([0]*(len(text2)+1))
        
        # dp[r][c] => LCS of text1[:r], text2[:c]
        
        for _r, _ in enumerate(text1):
            r = _r+1
            for _c, _ in enumerate(text2):
                c = _c+1
                if text1[_r] == text2[_c]:
                    dp[r][c] = dp[_r][_c]+1
                else:
                    dp[r][c] = max(dp[_r][c], dp[r][_c])
        
        return dp[len(text1)][len(text2)]