当前位置:网站首页>动态规划:最长公共子串和最长公共子序列
动态规划:最长公共子串和最长公共子序列
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]
边栏推荐
- [mathematical logic] normal form (conjunctive normal form | disjunctive normal form | major item | minor item | maximal item | minor item | principal conjunctive normal form | principal disjunctive no
- Yolov5 project based on QT
- The series of hyperbolic function in daily problem
- 监听对象中值变化及访问
- 二进制流转换成字节数组
- 为什么线程崩溃不会导致 JVM 崩溃
- Spark on yarn resource optimization ideas notes
- VS 2019 配置tensorRT生成engine
- [combinatorics] number of solutions of indefinite equations (number of combinations of multiple sets R | number of non negative integer solutions of indefinite equations | number of integer solutions
- Don't use the new Dede collection without the updated Dede plug-in
猜你喜欢

Bid farewell to artificial mental retardation: Mengzi open source project team received RMB 100 million financing to help NLP develop

The idea setting code is in UTF-8 idea Properties configuration file Chinese garbled

UMI route interception (simple and rough)

MongoDB复制集【主从复制】

softmax的近似之NCE详解

Unity3d RPG implementation (medium)

Spark on yarn resource optimization ideas notes

3D drawing example

Download and install node, NPM and yarn

PAT乙级“1104 天长地久”DFS优化思路
随机推荐
VS 2019 配置tensorRT生成engine
[combinatorics] Application of exponential generating function (multiple set arrangement problem | different balls in different boxes | derivation of exponential generating function of odd / even sequ
Mongodb installation & Deployment
Nce detail of softmax approximation
渤、黄海的潮汐特征
Limit of one question per day
Section 26 detailed explanation and demonstration of IPSec virtual private network configuration experiment - simulation experiment based on packettracer8.0
FileZilla Client下載安裝
Use of El tree search method
MySQL MAC download and installation tutorial
Elsevier latex 提交文章 pdftex.def Error: File `thumbnails/cas-email.jpeg‘ not found: using draf
模型转换onnx2engine
How to make backgroundworker return an object
[MySQL] the difference between left join, right join and join
The series of hyperbolic function in daily problem
[AI practice] Application xgboost Xgbregressor builds air quality prediction model (I)
[leetcode question brushing day 34] 540 Unique element in array, 384 Disrupt array, 202 Happy number, 149 Maximum number of points on a line
MongoDB主配置文件
C # webrequest post mode, based on "basic auth" password authentication mode, uploads files and submits other data using multipart / form data mode
递归:深度优先搜索