当前位置:网站首页>One brush 148 force deduction hot question-5 longest palindrome substring (m)
One brush 148 force deduction hot question-5 longest palindrome substring (m)
2022-07-03 16:57:00 【Tang and Song Dynasties】
subject :
Give you a string s, find s The longest palindrome substring in .
-------------
Example :
Input :s = "babad"
Output :"bab"
explain :"aba" It's the same answer .
Example 2:
Input :s = "cbbd"
Output :"bb"
Tips :
1 <= s.length <= 1000
s It consists only of numbers and English letters
-----------------------
reflection :
Dynamic programming method :
Palindromes naturally have 「 State shift 」 nature : A length is strictly greater than 22 After removing the first and last characters of the palindrome ,
The rest is still palindrome . conversely , If the first and last two characters of a string are not equal , Then this string must not be a palindrome .
「 Dynamic programming 」 According to this property, we get .
The first 1 Step : Define the State
dp[i][j] Express : Substring s[i..j] Whether it is palindrome substring ,
Here's the substring s[i..j] Defined as left closed right closed interval , That is, you can get s[i] and s[j]
The first 2 Step : Think about the state transfer equation
According to whether the first and last characters are equal , Need classified discussion :
dp[i][j] = (s[i] == s[j]) and dp[i + 1][j - 1]
explain :
「 Dynamic programming 」 Of 「 Bottom up 」 Ideas for solving problems , Most of the time, I am filling in a two-dimensional form .
because s[i..j] Express s A string of , therefore i and j The relationship is i <= j, Just fill in the part above the diagonal of this form ;
notice dp[i + 1][j - 1] You need to consider special circumstances :
If you remove s[i..j] Two character substrings at the beginning and end s[i + 1..j - 1] The length of is strictly less than 2( It doesn't form an interval ),
namely j - 1 - (i + 1) + 1 < 2 when ,
Put it in order j - i < 3, here s[i..j] Whether it is palindrome only depends on s[i] And s[j] Whether it is equal or not .
The conclusion is also intuitive :j - i < 3 Equivalent to j - i + 1 < 4,
That is, when the sub string s[i..j] The length of is equal to 2 Or equal to 3 When ,
s[i..j] Whether it is a palindrome is determined by s[i] And s[j] Equality determines .
The first 3 Step : Consider initializing
A single character must be a palindrome string , So initialize the diagonal to true, namely dp[i][i] = true.
According to the first 2 Description of step : When s[i..j] The length of is 22 when , Just judge s[i] Is it equal to s[j],
Therefore, the values on the diagonal of the two-dimensional table will not be referenced . So don't set dp[i][i] = true You can also get the right conclusion .
The first 4 Step : Consider output
Once you get it dp[i][j] = true, Just record the substring 「 length 」 and 「 The starting position 」.
There's no need to intercept , This is because intercepting strings also has performance consumption .
This principle should be followed in filling out the form : Always get whether the small string is the result of palindrome first ,
Then the large substring can refer to the judgment result of the small substring , So the order of filling in the form is very important ;
Code :
class Solution {
public String longestPalindrome(String s) {
int len = s.length();// Define variables to represent String length
if (len < 2) {
// If the string length is less than 2 Returns the string directly
return s;
}
int maxLen = 1;// Define variables to represent Number of palindrome characters
int begin = 0;// Start index of palindrome substring
// dp[i][j] Express s[i, j] Is it a palindrome string
boolean[][] dp = new boolean[len][len];// Define two-dimensional array storage All possible results
for (int i = 0; i < len; i++) {
// A single character is itself a palindrome string
dp[i][i] = true;
}
for (int j = 1; j < len; j++) {
// Recursive traversal : All elements above the diagonal of a two-dimensional array
for (int i = 0; i < j && i < len - 1; i++) {
if (s.charAt(i) != s.charAt(j)) {
// If two characters are not equal It's not a palindrome string
dp[i][j] = false;
} else {
// When it is a palindrome string , The number of characters is less than or equal to 3 individual It's a palindrome string
if (j - i < 3) {
dp[i][j] = true;
} else {
// Recursive judgment : When the characters on both sides of the boundary are equal , Continue to determine whether the characters in the inner layer are equal
dp[i][j] = dp[i + 1][j - 1];
}
}
// as long as dp[i][j] == true establish , It means substring s[i..j] It's palindrome. , At this point, record the palindrome length and starting position
if (dp[i][j] && j - i + 1 > maxLen) {
maxLen = j - i + 1;
begin = i;
}
}
}
// String cutting
return s.substring(begin, begin + maxLen);
}
}
Complexity analysis :
Time complexity :O(N^{
2}), here N Is the length of the string ;
Spatial complexity :O(N^{
2}) A two-dimensional table is used to record all possible situations
边栏推荐
- 执行脚本不认\r
- Atom QT 16_ audiorecorder
- To resist 7-Zip, list "three sins"? Netizen: "is the third key?"
- 跨境电商:外贸企业做海外社媒营销的优势
- ANOVA example
- QT serial port UI design and solution to display Chinese garbled code
- CC2530 common registers for port initialization
- [Jianzhi offer] 64 Find 1+2+... +n
- NLP four paradigms: paradigm 1: fully supervised learning in the era of non neural networks (Feature Engineering); Paradigm 2: fully supervised learning based on neural network (Architecture Engineeri
- 匯編實例解析--實模式下屏幕顯示
猜你喜欢

关于学习Qt编程的好书精品推荐

Pytorch 1.12 was released, officially supporting Apple M1 chip GPU acceleration and repairing many bugs
![[combinatorics] non descending path problem (number of non descending paths with constraints)](/img/89/bd1a2ddd9632ab5d4b4bee9336be51.jpg)
[combinatorics] non descending path problem (number of non descending paths with constraints)

Static program analysis (I) -- Outline mind map and content introduction

New features of C 10

What material is 12cr1movr? Chemical property analysis of pressure vessel steel plate 12cr1movr

Kotlin learning quick start (7) -- wonderful use of expansion

29:第三章:开发通行证服务:12:开发【获得用户账户信息,接口】;(使用VO类包装查到的数据,以符合接口对返回数据的要求)(在多处都会用到的逻辑,在Controller中可以把其抽成一个共用方法)
![[combinatorics] polynomial theorem (polynomial theorem | polynomial theorem proof | polynomial theorem inference 1 item number is the number of non negative integer solutions | polynomial theorem infe](/img/9d/6118b699c0d90810638f9b08d4f80a.jpg)
[combinatorics] polynomial theorem (polynomial theorem | polynomial theorem proof | polynomial theorem inference 1 item number is the number of non negative integer solutions | polynomial theorem infe

Aike AI frontier promotion (7.3)
随机推荐
CC2530 common registers for port initialization
Deep understanding of grouping sets statements in SQL
[JDBC] API parsing
建立自己的网站(23)
Data driving of appium framework for mobile terminal automated testing
Bcvp developer community 2022 exclusive peripheral first bullet
AcWing 第58 场周赛
MySQL converts comma separated attribute field data from column to row
Résolution de l'instance d'assemblage - - affichage à l'écran en mode réel
Alibaba P8 painstakingly sorted it out. Summary of APP UI automated testing ideas. Check it out
CC2530 common registers for watchdog
Zebras are recognized as dogs, and Stanford found the reason why AI made mistakes
Shentong express expects an annual loss of nearly 1billion
远程办公之如何推进跨部门项目协作 | 社区征文
C language string inversion
Daily code 300 lines learning notes day 10
What is the maximum number of concurrent TCP connections for a server? 65535?
mysql用户管理
Kotlin learning quick start (7) -- wonderful use of expansion
[combinatorics] recursive equation (constant coefficient linear homogeneous recursive equation | constant coefficient, linear, homogeneous concept description | constant coefficient linear homogeneous