蓝桥杯11.17:最长公共子序列

问题描述

给定两个字符串,寻找这两个字串之间的最长公共子序列。
输入格式
输入两行,分别包含一个字符串,仅含有小写字母。
输出格式
最长公共子序列的长度。
样例输入
abcdgh
aedfhb
样例输出
3
样例说明
最长公共子序列为a,d,h。
数据规模和约定
字串长度1~1000。

分析

这题是一道典型的动态规划题,设text1 = ‘abcdgh’, text2 = ‘aedfhb’
我们先用text2的第一个字母与text1做最长公共子序列

a b c d g h
a 1 1 1 1 1 1

再用text2的第二个字母与text1做最长公共子序列

a b c d g h
a 1 1 1 1 1 1
e 1 1 1 1 1 1

… …
最后得出表格:

a b c d g h
a 1 1 1 1 1 1
e 1 1 1 1 1 1
d 1 1 1 2 2 2
f 1 1 1 2 2 2
h 1 1 1 2 2 3
b 1 2 2 2 2 3

由此可以得出转移方程:

  • if text1[i] = text2[j] : dp[i][j] = dp[i - 1][j - 1] + 1]
  • else dp[i][j] = max(dp[i][j - 1], dp[i - 1][j - 1])

由于当text1[0] = text2[j] 或text1[i] = text2[0]时下标越界,所以优化表格如下所示:

# a b c d g h
# 0 0 0 0 0 0 0
a 0 1 1 1 1 1 1
e 0 1 1 1 1 1 1
d 0 1 1 1 2 2 2
f 0 1 1 1 2 2 2
h 0 1 1 1 2 2 3
b 0 1 2 2 2 2 3

算法实现

class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        m = len(text1) + 1
        n = len(text2) + 1
        text1 = '#' + text1
        text2 = '#' + text2
        dp = [[0 for each in range(m)]]
        for i in range(1, n):
            old = text2[i]
            dp.append([0])
            for j in range(1, m):
                if text1[j] == old:
                    dp[i].append(dp[i - 1][j - 1] + 1)
                else:
                    dp[i].append(max(dp[i - 1][j], dp[i][j - 1]))
        return dp[i][j]

算法优化

由于我们每次计算只用到最后的一行,所以可以将二维列表优化成一维:
初始列表:

0 0 0 0 0 0

第一次循环后:

1 1 1 1 1 1

第二次循环后:

1 1 1 1 1 1

第三次:

1 1 1 2 2 2

… …
结果:

1 2 2 2 2 3
class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        m = len(text1) + 1
        n = len(text2) + 1
        text1 = '#' + text1
        text2 = '#' + text2
        dp = [0 for each in range(m)]
        for i in range(1, n):
            old = text2[i]
            temp = 0
            for j in range(1, m):
                now = dp[j]
                if text1[j] == old:
                    dp[j] = temp + 1
                else:
                    dp[j] = max(dp[j], dp[j - 1])
                temp = now
        return dp[-1]
发布了100 篇原创文章 · 获赞 10 · 访问量 3418

猜你喜欢

转载自blog.csdn.net/qq_44315987/article/details/103116054