首页 > 试题广场 >

最长公共子序列(一)

[编程题]最长公共子序列(一)
  • 热度指数:6856 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定两个字符串 s1 和 s2,长度为 n 和 m  。求两个字符串最长公共子序列的长度。
所谓子序列,指一个字符串删掉部分字符(也可以不删)形成的字符串。例如:字符串 "arcaea" 的子序列有 "ara" 、 "rcaa" 等。但 "car" 、 "aaae" 则不是它的子序列。
所谓 s1 和 s2 的最长公共子序列,即一个最长的字符串,它既是 s1 的子序列,也是 s2 的子序列。
数据范围 : 。保证字符串中的字符只有小写字母。
要求:空间复杂度 O(n),时间复杂度
进阶:空间复杂度 O(n),时间复杂度

输入描述:
第一行输入一个整数 n 和 m ,表示字符串 s1 和 s2 的长度。
接下来第二行和第三行分别输入一个字符串 s1 和 s2。


输出描述:
输出两个字符串的最长公共子序列的长度
示例1

输入

5 6
abcde
bdcaaa

输出

2

说明

最长公共子序列为 "bc" 或 "bd" ,长度为2    
示例2

输入

3 3
abc
xyz

输出

0
n,m = list(map(int,input().split()))
s1=input()
s2=input()
shorterLength = min(n,m)
longerLength = max(n,m)
# 空间复杂度O(mn)
# dp = [[0]*(longerLength+1) for i in range(shorterLength+1)]
# if shorterLength==m:
#     s1,s2 = s2,s1
# for i in range(1,shorterLength+1):
#     for j in range(1,longerLength+1):
#         if s1[i-1]==s2[j-1]:
#             dp[i][j] = dp[i-1][j-1]+1
#         else:
#             dp[i][j] = max(dp[i-1][j],dp[i][j-1])
# print(dp[shorterLength][longerLength])

# 空间复杂度O(min(m,n))
dp1 = [0]*(shorterLength+1)
dp2 = [0]*(shorterLength+1)
if shorterLength==m:
    s1,s2 = s2,s1
for i in range(1,longerLength+1):
    for j in range(1,shorterLength+1):
        if s2[i-1]==s1[j-1]:
            dp2[j]=dp1[j-1]+1
        else:
            dp2[j]=max(dp2[j-1],dp1[j])
    dp1 = dp2.copy()
print(dp2[shorterLength])

发表于 2023-08-05 22:56:41 回复(0)
import sys

i = 0
m = n = 0
s1 = s2 = ""
for line in sys.stdin:
    a = line.split()
    if i == 0:
        m, n = int(a[0]), int(a[1])
    elif i == 1:
        s1 = a[0]
    else:
        s2 = a[0]
    i += 1
dp = [[0 for _ in range(n+1)] for _ in range(m+1)]

for i in range(m):
    for j in range(n):
        if s1[i] == s2[j]:
            dp[i+1][j+1] = dp[i][j] + 1
        else:
            dp[i+1][j+1] = max(dp[i+1][j], dp[i][j+1])
print(dp[m][n])

发表于 2023-03-16 16:50:00 回复(0)