Give you a string s
and find the longest palindrome substring in s
Example 1:
Input: s = "babad"
Output: "bab"
Explanation: "aba" is also an answer that meets the meaning of the question.
Example 2:
Input: s = "cbbd"
Output: "bb"
Example 3:
Input: s = "a"
Output: "a"
Example 4:
Input: s = "ac"
Output: "a"
Problem-solving ideas
Using dynamic programming, the state transition equation is as follows:
dp[i][j] = (s[i] == s[j]) && (i - j < 3 || dp[j + 1][i - 1])
If s[i] == s[j]
appears, then if i - j < 3
or dp[j + 1][i - 1]
is also a palindrome string, then the string from j
to i
is also a palindrome string.
i - j < 3
corresponds to three situations, the first is three characters, the beginning and the end are the same, no matter what character is in the middle, it is a palindrome, the second is two characters, both are the same, obviously also a palindrome, and the third is There is only one character, and a character itself is also a palindrome
Java implementation:
class Solution {
public String longestPalindrome(String s) {
if (s == null || s.length() == 0) return s;
int len = s.length();
int start = 0;
int maxLen = 1;
boolean[][] dp = new boolean[len][len];
for (int i=0; i<len; i++) {
for (int j=0; j<=i; j++) {
if (i == j) {
// 初始条件
// 一个字符本身就是回文串
dp[i][i] = true;
continue;
}
if (s.charAt(i) == s.charAt(j)) {
if (i - j <= 2 || dp[j + 1][i - 1]) {
// 状态转移方程
dp[j][i] = true;
if (i - j + 1 > maxLen) {
// 记录最大长度和起始下标
maxLen = i - j + 1;
start = j;
}
}
}
}
}
// 返回字符串
return s.substring(start, start + maxLen);
}
}
JS implementation:
function longestPalindrome(s) {
if (s == null || s.length == 0) return s;
let len = s.length;
let start = 0;
let maxLen = 1;
let dp = gen2DArray(len, len);
for (let i=0; i<s.length; i++) {
for (let j=0; j<=i; j++) {
if (i == j) {
dp[i][i] = true;
continue;
}
if (s[i] == s[j]) {
if (i - j <= 2 || dp[j + 1][i - 1]) {
dp[j][i] = true;
if (i - j + 1 > maxLen) {
maxLen = i - j + 1;
start = j;
}
}
}
}
}
return s.substring(start, start + maxLen)
}
function gen2DArray(a, b) {
let res = [];
for (let i=0; i<a; i++) {
res.push([]);
for (let j=0; j<b; j++) {
res[i][j] = false;
}
}
return res;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。