当前位置:网站首页>Dynamic programming: longest common substring and longest common subsequence
Dynamic programming: longest common substring and longest common subsequence
2022-07-03 03:32:00 【My family Dabao is the cutest】
The longest public substring
Given two strings , Find the longest identical substring , For example, stator string asdfas and werasdfaswer, The longest substring shared by the two substrings is asdfas This string .
Again , At first glance, this problem is dynamic programming , We first list the state transition equation , Suppose two strings are separated by i,j The length of the longest common substring at the end is dp[i][j], When A[i]==B[j] when ,dp[i][j]=dp[i-1][j-1]+1, If these two characters are not equal , That is to say A[i],B[j] The two strings ending with are not common substrings , here 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)
Longest common subsequence
Common subsequences do not need to be continuous , therefore , Even if two strings are not equal ,dp[i][j] Not for 0. The current two characters are not equal ,t1[i]!=t2[j] Words , Then the minimum length is also dp[i-1][j-1], But that's not enough , Because we want to get as much length as possible in the previous comparison . Then when the current characters are not equal , You should put the current character into the previous comparison , Then there must be dp[i][j-1] and dp[i-1][j]>=dp[i][j]. Simply speaking ,dp[i][j] The value of should be from dp[i-1][j-1],dp[i][j-1],dp[i-1][j] Choose from the three , but dp[i][j]≤ The other two , So compare the other two , Take the larger .
The state representation we define f Array and text Array subscripts are from 1 At the beginning , And the title gives text Array subscript is from 0 At the beginning , For one A corresponding , In judging text1 and text2 When the last bit of the array is equal , One wrong place forward , That is to use text1[i - 1] and text2[j - 1] To judge .
Here's why f Array and text Arrays are defined as subscripts from 1 Start . The reason is because of the state transition equation f[i][j] = max(f[i - 1][j],f[i][j - 1]), When our f Array defined as subscript from 1 After the start , We can make no extra judgment on the problem of subscript out of bounds in the code . In fact, we can also find a problem , Is the original array given by the topic , such as text Array , If subscript from 1 At the beginning , The state representation will be clearer , The process of deriving the state transition equation will also be better understood .
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]
边栏推荐
- Advanced redis applications [password protection, data persistence, master-slave synchronization, sentinel mode, transactions] [not completed yet (semi-finished products)]
- FileZilla Client下载安装
- MongoDB安装 & 部署
- Summary of electromagnetic spectrum
- 900w+ data, from 17s to 300ms, how to operate
- Positioning (relative positioning, absolute positioning, fixed positioning, Z-index) 2022-2-11
- Model transformation onnx2engine
- FileZilla client download and installation
- Converts a timestamp to a time in the specified format
- 小程序获取用户头像和昵称
猜你喜欢
随机推荐
Summary of determinant knowledge points in Chapter 1 of Linear Algebra (Jeff's self perception)
New programmers use the isXXX form to define Boolean types in the morning, and are discouraged in the afternoon?
com. fasterxml. jackson. databind. Exc.invalidformatexception problem
Change and access of median value of listening object
基于Qt的yolov5工程
Use three JS make a simple 3D scene
Spark on yarn resource optimization ideas notes
The series of hyperbolic function in daily problem
[pyg] understand the messagepassing process, GCN demo details
Elsevier latex submitted the article pdftex def Error: File `thumbnails/cas-email. jpeg‘ not found: using draf
递归使用和多维数组对象变一维数组对象
Basic operations of mongodb [add, delete, modify, query]
简易版 微信小程序开发之for指令、上传图片及展示效果优化
Application of derivative in daily question
Lvgl usage experience
shardingsphere动态数据源
C programming learning notes [edited by Mr. Tan Haoqiang] (Chapter III sequence programming) 03 operators and expressions
Unity3d RPG implementation (medium)
Nanning water leakage detection: warmly congratulate Guangxi Zhongshui on winning the first famous brand in Guangxi
The difference between static web pages and dynamic web pages & the difference between Web1.0 and Web2.0 & the difference between get and post








