C++:
枚举中心点然后及时剪枝应该是最快的,但是我没写,我就用最经典的做法来解决了,DP,但是三种语言的时间效率差别真的有点大,不明白LeetCode的测试样例,难道对不同的语言还不太一样?不会吧,已经差出数量级了。
class Solution {
public:
int dp[1009][1009];
string longestPalindrome(string s) {
int ansl=0,ansr=0,ans=1;
int L=s.length();
memset(dp,-1,sizeof(dp));
for(int i=0;i<L;i++){
dp[i][i]=1;
}
for(int i=2;i<=L;i++){
for(int j=0;j<=L-i;j++){
int l=j;
int r=j+i-1;
if(s[l]==s[r]){
if(r-l>=2){
if(dp[l+1][r-1]!=-1){
dp[l][r]=r-l+1;
if(dp[l][r]>ans){
ans=dp[l][r];
ansl=l;
ansr=r;
}
}
}
else{
if(dp[l+1][r]!=-1||dp[l][r-1]!=-1){
dp[l][r]=r-l+1;
if(dp[l][r]>ans){
ans=dp[l][r];
ansl=l;
ansr=r;
}
}
}
}
}
}
return s.substr(ansl,ansr-ansl+1);
}
};
Java:
几乎跟C一样的代码,结果TLE了,不知所措。
class Solution {
public int dp[][]=new int[1009][1009];
public String longestPalindrome(String s) {
int ansl=0,ansr=0,ans=1;
int L=s.length();
for(int i=0;i<L;i++){
for(int j=0;j<L;j++){
if(i==j){
dp[i][j]=1;
continue;
}
dp[i][j]=-1;
}
}
for(int i=2;i<=L;i++){
for(int j=0;j<=L-i;j++){
int l=j;
int r=j+i-1;
if(s.charAt(l)==s.charAt(r)){
if(r-l>=2){
if(dp[l+1][r-1]!=-1){
dp[l][r]=r-l+1;
if(dp[l][r]>ans){
ans=dp[l][r];
ansl=l;
ansr=r;
}
}
}
else{
if(dp[l+1][r]!=-1||dp[l][r-1]!=-1){
dp[l][r]=r-l+1;
if(dp[l][r]>ans){
ans=dp[l][r];
ansl=l;
ansr=r;
}
}
}
}
}
}
return s.substring(ansl,ansr+1);
}
}
Python:
速度慢到爆炸,虽然A了。同样的算法,c++ 143 ms,java TLE,Python 7562ms
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
ansl=0
ansr=0
ans=1
L=s.__len__()
dp=[[-1 for x in range(L)] for y in range(L)]
for i in range(L):
dp[i][i]=1
for i in range(2,L+1):
for j in range(L-i+1):
l=j
r=j+i-1
if s[l]==s[r]:
if r-l>=2:
if dp[l+1][r-1]!=-1:
dp[l][r]=r-l+1
if dp[l][r]>ans:
ans=dp[l][r]
ansl=l
ansr=r
else:
if dp[l+1][r]!=-1 or dp[l][r-1]!=-1:
dp[l][r]=r-l+1
if dp[l][r]>ans:
ans=dp[l][r]
ansl=l
ansr=r
return s[ansl:ansr+1]