描述
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000
给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000
例子
思路
- 方法1 龙卷风法,找龙眼
两种龙眼:一种bab,一种baab,即(i,i)和(i,i+1)
- 方法2 动态规划
答案 - java
//方法1
class Solution {
private int max_i=0,max_j=0;
public void check(String s, int i, int j) {
while(i>=0 && j<=s.length()-1){
if(s.charAt(i)==s.charAt(j)) {
i--;
j++;
}else break;
}
i=i+1;
j=j-1;
if(j-i>max_j-max_i) {
max_i=i;
max_j=j;
}
}
public String longestPalindrome(String s) {
if(s.length()==0) return "";
for(int i=0; i<s.length(); i++) {
check(s,i,i);
check(s,i,i+1);
}
return s.substring(max_i, max_j+1);
}
}
//方法2
class Solution {
public String longestPalindrome(String s) {
if(s.length()==0) return "";
boolean[][] arr = new boolean[s.length()][s.length()];
int max_i=0, max_j=0;
//r为字符的长度
for(int r=1; r<=s.length(); r++) {
for(int i=0; i+r-1<s.length(); i++) {
int j=i+r-1;
//长度为1
if(i==j) arr[i][j]=true;
//长度为2
else if(i+1==j && s.charAt(i)==s.charAt(j)) arr[i][j]=true;
else if(i+1<=j-1 && s.charAt(i)==s.charAt(j)) arr[i][j]=arr[i+1][j-1];
if(arr[i][j]==true && j-i>max_j-max_i){
max_i=i;
max_j=j;
}
}
}
return s.substring(max_i, max_j+1);
}
- python
*方法1*
class Solution:
def check(self, s:string, a:int,b:int)->str:
while a>=0 and b<len(s) and s[a]==s[b]:
a-=1
b+=1
a+=1
b-=1
return s[a:b+1]
def longestPalindrome(self, s: str) -> str:
res = ""
for i in range(len(s)):
s2 = self.check(s,i,i)
s3 = self.check(s,i,i+1)
if len(res)<len(s2):
res = s2
if len(res)<len(s3):
res = s3
return res
*方法2*
def longestPalindrome(self, s: str) -> str:
res = ""
dp=[[0]*len(s) for i in range(len(s))]
for r in range(len(s)):#r=j-i 0~len-1 r为0时是一个元素,为1时为两个元素在一起
for i in range(len(s)-r): #i+r<=len-1(最大下标)
j=i+r
if i==j:
dp[i][j]=1
if i+1==j:
dp[i][j]=1 if s[i]==s[j] else 0
if i+2<=j:
dp[i][j]=dp[i+1][j-1] and s[i]==s[j]
if dp[i][j] and j-i+1>len(res):
res=s[i:j+1]
- c++
*方法1*
class Solution {
private:
string check(string s, int a, int b){
while (a>=0 && b<=s.size() && s[a]==s[b])
{
a--;
b++;
}
a++;
b--;
return s.substr(a,b-a+1);
}
public:
string longestPalindrome(string s) {
string res("");
for (int i=0; i<s.size(); i++)
{
string s2 = check(s,i,i);
string s3 = check(s,i,i+1);
if (res.size()<s2.size())
res=s2;
if (res.size()<s3.size())
res=s3;
}
return res;
}
};
*方法2*
class Solution {
public:
string longestPalindrome(string s) {
int L = s.size();
string res("");
vector<vector<int>> dp(L,vector<int>(L));//全是0的二维数组
for(int r=0; r<L; r++)
for (int i=0; i<L-r; i++)
{
int j=i+r;
if (i==j)
dp[i][j]=1;
if (i+1==j)
dp[i][j]=s[i]==s[j]?1:0;
if (i+2<=j)
dp[i][j]=(dp[i+1][j-1] && s[i]==s[j])?1:0;
if (dp[i][j] && j-i+1>res.size())
res = s.substr(i,j-i+1);
}
return res;
}
};