两个字符串的最长公共子串和最长公共子序列

最长公共子串

代码

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        # 最长公共子串思路,会有案例超时
        if not haystack and not needle: return 0
        if not haystack and needle: return -1
        if haystack and not needle: return 0


        m, n = len(haystack), len(needle)
        record = [[0 for _ in range(n)] for _ in range(m)]
        maxlen, maxend = 0, 0
        for row in range(m):
            for col in range(n):
                if haystack[row] == needle[col]:
                    if not row or not col:
                        record[row][col] = 1
                    else:
                        record[row][col] = record[row-1][col-1] + 1
                if record[row][col] > maxlen:
                    maxlen = record[row][col]
                    maxend = row
        if maxlen == n:
            return maxend - maxlen + 1
        else:
            return -1

最长公共子序列

代码

class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        m, n = len(text1), len(text2)
        # dp的索引是行代表text1的子串长度,列代表text2的子串长度,值是两个子串(从左边开始的子串)的最长公共子序列
        dp = [[0 for _ in range(n+1)] for _ in range(m+1)]
        helper = [[0 for _ in range(n+1)] for _ in range(m+1)]
        for row in range(1, m + 1):
            for col in range(1, n + 1):
                # 对角过来
                # 注意row,col是长度, 减去1才是子串的末尾
                if text1[row-1] == text2[col-1]:
                    dp[row][col] = dp[row-1][col-1] + 1
                # 从左边过来
                elif dp[row][col-1] > dp[row-1][col]:
                    dp[row][col] = dp[row][col-1]
                    helper[row][col] = 1
                # 从上边过来
                else:
                    dp[row][col] = dp[row-1][col]
                    helper[row][col] = -1
        def printlen(row, col):
            if not row or not col: return
            if helper[row][col] == 0:
                # 递归到末尾
                printlen(row-1, col-1)
                # 注意对应长度-1才是字符所在位置
                print(text1[row-1], end=' ')
            elif helper[row][col] == 1:
                printlen(row, col-1)
            else:
                printlen(row-1, col)
        printlen(m, n)
        return dp[m][n]



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值