题目:
- Total Accepted: 202411
- Total Submissions: 805973
- Difficulty: Medium
- Contributor: LeetCode
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example:
Input: "cbbd" Output: "bb"
动态规划方法:
我们要知道如何避免不必要的重新计算,验证回文。如果我们已经知道的'bab”''bab”是回文,那么可知,“'ababa”''ababa”必是回文,因为左右两端字母是一样的。
定义p(i,j)p(i,j)如下:
P(i,j)={true,if the substring Si…Sj is a palindromefalse,otherwise. P(i,j)={true,if the substring Si…Sj is a palindromefalse,otherwise.
因此,
P(i, j) = ( P(i+1, j-1) \text{ and } S_i == S_j )P(i,j)=(P(i+1,j−1) and Si==Sj)
基本情况如下:
P(i, i) = trueP(i,i)=true
P(i, i+1) = ( S_i == S_{i+1} )P(i,i+1)=(Si==Si+1)
复杂度分析
.Time complexity : O(n^2)O(n2). This gives us a runtime complexity of O(n^2)O(n2).
.Space complexity : O(n^2)O(n2). It uses O(n^2)O(n2) space to store the table.
这是以abade为例,得到的dp矩阵:
给出代码:
public
String longestPalindrome(String s) {
boolean
[][] flag =
new
boolean
[s.length()][s.length()];
int
maxlen =
0
,start =
0
;
for
(
int
i =
0
;i < s.length(); i++){
flag[i][i] =
true
;
maxlen =
1
;
start = i;
}
for
(
int
i =
0
;i < s.length()-
1
; i++)
if
(s.charAt(i)==s.charAt(i+
1
)){
flag[i][i+
1
] =
true
;
maxlen =
2
;
start = i;
}
for
(
int
len =
3
; len<= s.length(); len++)
for
(
int
i =
0
;i < s.length()-len+
1
; i++){
int
j = i+len-
1
;
if
(s.charAt(i)==s.charAt(j)&&flag[i+
1
][j-
1
]==
true
){
flag[i][j] =
true
;
maxlen = len;
start = i;
}
}
return
s.substring(start, start+maxlen);
}