当前位置:网站首页>动态规划:最长公共子串和最长公共子序列
动态规划:最长公共子串和最长公共子序列
2022-07-03 03:28:00 【我家大宝最可爱】
最长公共子串
给定两个字符串,求出最长的相同的子串,例如给定子串asdfas
和werasdfaswer
,其中两个子串串中共有的最长子串就是asdfas
这个字符串。
同样,这道题一看就是动态规划,我们首先列出状态转移方程,假设两个字符串分别以i,j
为结尾的最长公共子串长度为dp[i][j]
,当A[i]==B[j]
时,dp[i][j]=dp[i-1][j-1]+1
,如果这两个字符不相等,也就是说以A[i],B[j]
为结尾的这两个字符串就不是公共子串,此时dp[i][j]=0
a | s | d | f | a | s | ||||
w | e | r | a | s | d | f | a | s | w |
s1 = input()
s2 = input()
n1 = len(s1)
n2 = len(s2)
dp = [[0 for _ in range(n2)] for _ in range(n1)]
max_len = 0
for i,x in enumerate(s1):
for j,y in enumerate(s2):
if x == y:
if i == 0 or j == 0:
dp[i][j] = 1
else:
dp[i][j] = dp[i-1][j-1] + 1
if dp[i][j] > max_len:
max_len = dp[i][j]
print(max_len)
最长公共子序列
公共子序列不需要连续,因此,即使两个字符串不相等,dp[i][j]
也不会为0。当前两个字符不等,t1[i]!=t2[j]
的话,那么长度最少也是dp[i-1][j-1]
,但这还不够,因为我们希望拿到之前的比较中尽可能大的长度。那么当前字符已经不相等的情况下,就应该把当前的字符也放入到之前的比较中,那么一定有dp[i][j-1]和dp[i-1][j]>=dp[i][j]
。简单来说,dp[i][j]
的值应该从dp[i-1][j-1],dp[i][j-1],dp[i-1][j]
三者中取,但dp[i][j]≤另外两个,故比较另外两个,取较大的。
我们定义的状态表示f数组和text数组下标均是从1开始的,而题目给出的text数组下标是从0开始的,为了一 一对应,在判断text1和text2数组的最后一位是否相等时,往前错一位,即使用text1[i - 1]和text2[j - 1]来判断。
这里解释一下为什么f数组和text数组均定义成下标从1开始。原因是因为状态转移方程 f[i][j] = max(f[i - 1][j],f[i][j - 1]), 当我们的f数组定义成下标从1开始以后,我们就可以在代码中不用对下标越界问题做出额外判断。其实我们也可以发现一个问题,就是题目给定的原数组,比如text数组,如果下标从1开始的话,状态表示会更加的清晰,推导状态转移方程的过程也会更加好理解。
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
m, n = len(text1), len(text2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if text1[i - 1] == text2[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[m][n]
边栏推荐
- MongoDB复制集【主从复制】
- Applet get user avatar and nickname
- 基于Qt的yolov5工程
- Pytorch multi card distributed training distributeddataparallel usage
- Vs Code configure virtual environment
- FileZilla client download and installation
- Gavin teacher's perception of transformer live class - rasa project's actual banking financial BOT Intelligent Business Dialogue robot architecture, process and phenomenon decryption through rasa inte
- @Accessors annotation function specifies that the prefix follows the hump naming
- Advanced redis applications [password protection, data persistence, master-slave synchronization, sentinel mode, transactions] [not completed yet (semi-finished products)]
- C # webrequest post mode, based on "basic auth" password authentication mode, uploads files and submits other data using multipart / form data mode
猜你喜欢
el-tree搜索方法使用
docker安装及启动mysql服务
Vs 2019 configuration du moteur de génération de tensorrt
VS 2019安装及配置opencv
VS 2019 配置tensorRT生成engine
Pytoch lightweight visualization tool wandb (local)
Introduction to mongodb
Idea format code idea set shortcut key format code
Application of derivative in daily question
Introduction à mongodb
随机推荐
模型转换onnx2engine
递归:快速排序,归并排序和堆排序
Pat class B "1104 forever" DFS optimization idea
el-tree搜索方法使用
Réglez la hauteur et lancez le système. Currenttimemillis catton
[combinatorics] Application of exponential generating function (multiple set arrangement problem | different balls in different boxes | derivation of exponential generating function of odd / even sequ
numpy之 警告VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences
机械臂速成小指南(八):运动学建模(标准DH法)
Compare float with 0
[algebraic structure] group (definition of group | basic properties of group | proof method of group | commutative group)
[combinatorics] brief introduction to generating function (definition of generating function | Newton binomial coefficient | commonly used generating function | correlation with constant | correlation
[combinatorics] basic counting principle (addition principle | multiplication principle)
Solve high and send system Currenttimemillis Caton
Vs 2019 configuration du moteur de génération de tensorrt
New programmers use the isXXX form to define Boolean types in the morning, and are discouraged in the afternoon?
QT based tensorrt accelerated yolov5
解决高并发下System.currentTimeMillis卡顿
Don't use the new Dede collection without the updated Dede plug-in
Gavin teacher's perception of transformer live class - rasa project's actual banking financial BOT Intelligent Business Dialogue robot architecture, process and phenomenon decryption through rasa inte
Section 26 detailed explanation and demonstration of IPSec virtual private network configuration experiment - simulation experiment based on packettracer8.0