当前位置:网站首页>Dynamic programming: Longest palindrome substring and subsequence
Dynamic programming: Longest palindrome substring and subsequence
2022-07-03 03:39:00 【My family Dabao is the cutest】
1. Palindrome string
Palindrome string is the same string read forward and backward , for example aba,aabb etc. , Given a string , Find the longest text substring . Note that substring refers to continuous
1.1 Expand left and right
The idea of left-right expansion is very interesting , If a problem uses the idea of left-right expansion , For so long, it is directly set in two ranges l,r, In this way, the parity problem can be avoided
A very direct idea is to start with a character , Start searching on both sides , Then match whether the characters are equal
| <— Search left | A certain character | Search right —> | |
|---|---|---|---|
| character string | a | b | a |
| Search boundaries | l | r |
It's easy to think of two situations, odd and even , When odd (‘aba’) when l=r=i, Then move to both sides , When it is even (‘aabb’) when l=i,r=i+1
def helper(s,l,r):
while l >= 0 and r < len(s) and s[l] == s[r]:
l -= 1
r += 1
return s[l+1:r]
def longs(s):
res = ''
for i in range(len(s)):
tmp = helper(s,i,i) # Odd number
if len(tmp) > len(res):res = tmp
tmp = helper(s,i,i+1) # even numbers
if len(tmp) > len(res):res = tmp
print(len(res))
s = input()
n = len(s)
longs(s)
1.2 Dynamic programming
The idea of dynamic planning is also very simple , If i+1~j-1 The palindrome string , So if s[i]==s[j] be i~j The string between is also a palindrome substring , If it's not equal , Then it's not a palindrome substring , Thus, the state transition equation can be listed dp[i][j]=dp[i+1][j-1] and s[i]==s[j]. Then we consider the initial conditions , If i==j be dp[i][i]=True, When a character is positive, the palindrome string , Two and three characters are dp[i][j] = (s[i] == s[j]), Just consider the characters on both sides .
You can see , Calculation dp[i][j] Used the future state dp[i+1][j], therefore i Reverse iteration is required , That is, large to small .
| Original string | a | b | c | a | c | b | a |
|---|---|---|---|---|---|---|---|
| Subsequence 1 | a | b | b | a |
class Solution:
def longestPalindrome(self, s: str) -> str:
n = len(s)
dp = [[False for j in range(n)] for i in range(n)]
max_len = 0
max_str = ''
for i in range(n-1,-1,-1):
for j in range(i,n):
if s[i] == s[j]:
if j-i<=2:
dp[i][j] = True
else:
dp[i][j] = dp[i+1][j-1]
if dp[i][j] and j - i + 1 > max_len:
max_len = j - i + 1
max_str = s[i:j+1]
return max_str
The longest palindrome subsequence
One of the main differences between subsequence and substring is whether it is connected , Characters do not need hyphenation , for instance
| Original string | a | b | c | a | b | c | a |
|---|---|---|---|---|---|---|---|
| Subsequence 1 | a | b | b | a | |||
| Subsequence 2 | a | c | c | a | |||
| Subsequence 3 | a | a | a | ||||
| Subsequence 4 | a | c | a | c | a | ||
| Subsequence 5 | a | b | a | b | a | ||
| Subsequence n | … |
You can see that palindrome subsequences do not need to be continuous at all , Now the problem is how to solve the longest subsequence ? If we find i+1~j-1 The longest subsequence between , So how to solve i~j The longest subsequence between ?
| i | i+1 | j-1 | j | |||||
|---|---|---|---|---|---|---|---|---|
| s[i] | a | b | c | a | b | c | a | s[j] |
We assume that dp[i+1][j-1] Is string i+1~j-1 The length of the longest palindrome subsequence of ,
- When
s[i]==s[j]when , Yesdp[i][j] = dp[i+1][j-1]+2
| i | i+1 | j-1 | j | |||||
|---|---|---|---|---|---|---|---|---|
| s[i] | a | b | c | a | b | c | a | s[j] |
- When
s[i]!=s[j]when , It's interesting at this time , It can also be divided into two situations , The first kind of time demandi+1~jThe longest palindrome sequence between , The second is to aski~j-1The longest palindrome subsequence between
| i | i+1 | j-1 | j | ||||||
|---|---|---|---|---|---|---|---|---|---|
| original | s[i] | a | b | c | a | b | c | a | s[j] |
i+1~j | a | b | c | a | b | c | a | s[j] | |
i~j-1 | s[i] | a | b | c | a | b | c | a |
At this time there is dp[i][j]=max(dp[i][j-1],dp[i+1][j])
We have got the state transition equation , The next step is to see base, You can know dp[i][i]=1, Because we have always been i~j, So there is j>i, If j<i, Then it is impossible to get the palindrome sequence , So there is dp[i][j]=0 if j < i
Now there is only one boundary problem , seek dp[i][j] Need to use dp[i+1][j], That is to solve i The position of the future is used i+1 Location , In order to ensure normal calculation , We need to i Update in a decreasing way ,j It uses j and j-1, So use incremental calculation
def longestPalindromeSubseq(self, s: str) -> int:
n = len(s)
dp = [[1 if i==j else 0 for i in range(n)] for j in range(n)]
for i in range(n-1,-1,-1):
for j in range(i+1,n):
if s[i] == s[j]:
dp[i][j] = dp[i+1][j-1] + 2
else:
dp[i][j] = max(dp[i+1][j],dp[i][j-1])
return dp[0][-1]
边栏推荐
- 如何迈向IPv6之IPv6过渡技术-尚文网络奎哥
- LVGL使用心得
- [mathematical logic] propositions and connectives (propositions | propositional symbolization | truth connectives | no | conjunction | disjunction | non truth connectives | implication | equivalence)
- PHP generates PDF tcpdf
- 递归使用和多维数组对象变一维数组对象
- Numpy warning visibledeprecationwarning: creating an ndarray from ragged needed sequences
- Vs 2019 installation and configuration opencv
- Dynamic programming: longest common substring and longest common subsequence
- Tidal characteristics of the Bohai Sea and the Yellow Sea
- Separable bonds and convertible bonds
猜你喜欢

umi 路由拦截(简单粗暴)
![C programming learning notes [edited by Mr. Tan Haoqiang] (Chapter III sequence programming) 05 data input and output](/img/38/9c460fc58b62609dd02e7c61207ae6.jpg)
C programming learning notes [edited by Mr. Tan Haoqiang] (Chapter III sequence programming) 05 data input and output

Lvgl usage experience

Elsevier latex submitted the article pdftex def Error: File `thumbnails/cas-email. jpeg‘ not found: using draf

Summary of electromagnetic spectrum

MongoDB简介

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

编译文件时报错:错误: 编码GBK的不可映射字符

MySQL MAC download and installation tutorial

Tidal characteristics of the Bohai Sea and the Yellow Sea
随机推荐
机械臂速成小指南(八):运动学建模(标准DH法)
IPv6 transition technology-6to4 manual tunnel configuration experiment -- Kuige of Shangwen network
简易版 微信小程序开发之for指令、上传图片及展示效果优化
动态规划:最长公共子串和最长公共子序列
FileZilla Client下载安装
Avec trois. JS fait une scène 3D simple
node,npm以及yarn下载安装
[algebraic structure] group (definition of group | basic properties of group | proof method of group | commutative group)
Captura下载安装及在Captura配置FFmpeg
Learning notes of C programming [compiled by Mr. Tan Haoqiang] (Chapter III sequence programming) 04 C sentence
Advanced redis applications [password protection, data persistence, master-slave synchronization, sentinel mode, transactions] [not completed yet (semi-finished products)]
MongoDB簡介
Null and undefined
Application of derivative in daily question
Convert binary stream to byte array
shardingsphere动态数据源
Applet get user avatar and nickname
Change and access of median value of listening object
Yolov5 project based on QT
Simple wechat applet development page Jump, data binding, obtaining user information, obtaining user location information