Leetcode刷题笔记-两个字符串比较dp

本文记录了LeetCode中涉及字符串比较和编辑距离的题目,包括Longest Common Subsequence、The Most Similar Path in a Graph、Edit Distance、Interleaving String和Regular Expression Matching。特别强调了Edit Distance和Regular Expression Matching的DP解法,同时提到需要重新审视的题目,如583. Delete Operation for Two Strings。
摘要由CSDN通过智能技术生成

1143. Longest Common Subsequence

class Solution:
    def longestCommonSubsequence(self, a: str, b: str) -> int:
        # if a[i] == b[j]: dp[i][j] = dp[i-1][j-1] + 1
        # if a[i] != b[j]: dp[i][j] = max(dp[i-1][j], dp[i][j-1])
        # dp[i][j] i, j is the number of chars in each string
        n, m = len(a), len(b)
        dp = [[0 for _ in range(m+1)] for _ in range(n+1)]
        # i or j is 0, means one of the string size is 0, the common is 0

        for i in range(1, n+1):
            for j in range(1, m+1):
                if a[i-1] == b[j-1]:
                    dp[i][j] = dp[i-1][j-1] + 1
                else:
                    dp[i][j] = max(dp[i-1][j], dp[i][j-1])
        
        return dp[-1][-1]

 

1548. The Most Similar Path in a Graph

class Solution:
    def mostSimilar(self, n: int, roads: List[List[int]], names: List[str], tp: List[str]) -> List[int]:
        # 思路和2个字符串找最长重复的子串思路一样 用二维dp
        '''
        Let's first calculate the minimum edit distance without worrying about the path. We can use 2D DP to do that:

        dp[i][v] means the minimum edit distance for tp[:i+1] ending with city v.
        The trainsition function is:

        dp[i][v] = min(dp[i-1][u] + edit_cost(v)) for all edges (u, v)
        , where edit_cost(v) at index i is names[v] != tp[i].

        And
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值