LeetCode OJ 5 Longest Palindromic Substring
Posted Z-Pilgrim
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode OJ 5 Longest Palindromic Substring相关的知识,希望对你有一定的参考价值。
https://leetcode.com/problems/longest-palindromic-substring/
感觉也许O(n)算法可以搞定,于是DP之,各种胡思乱想,于是各种BUG 。。。。。写死了,然后O(n*n)过掉的,搜下题解,然后发现一个打脸的事情,TM我写过博客http://blog.csdn.net/u011026968/article/details/26093495
O(n^2)的dp解法(对非ACM选手够了)
class Solution
public:
string longestPalindrome(string s)
// dp[i]:以i结尾的最长...
// dp[i] = dp[i-1] + 2 (if xxx) or 1
if(!s.size()) return "";
int dp[s.size()+1][s.size()+1];
memset(dp, 0, sizeof(dp));
int ans = 0, pos = 0;
// for (int i = 0; i<s.size(); i++)
// dp[i][i] = 1;
//
// for(int len = 1; len <= s.size(); len++)
for(int i = s.size()-1; i >=0; i--)
for(int j=i;j< s.size(); j++)
if(j == i)
dp[i][j] = 1;
else
dp[i][j] = 0;
if(s[i] == s[ j ])
if(j-i == 1) // i+1 > j-1 2>j-i
dp[i][j] = 1;
else
dp[i][j] = dp[i+1][j-1]; //max(dp[i][j], dp[i+1][j-1]+2);
if(dp[i][j] && j-i+1 > ans)
ans = j-i+1;
pos = i;
return s.substr(pos, ans);
;
就是这个O(n)算法啊,TMD 真是一朝不做ACM,各种算法全忘光
O(n)算法如下,没的说,裸地暴力
#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#include <cstring>;
using namespace std;
class Solution
public:
string longestPalindrome(string s)
int st=0,mx=1;
int dp[2005];
if(s.size() == 0)return "";
dp[0]=1;
for(int i=0;i<s.size();i++)
if(i+1<s.size())
int cnt=0,flag=0;
if(s[i] == s[i+1])
cnt=2;
flag=1;
for(int j=i-1;j>=0 && j+cnt+1<s.size();j--)
if(s[j] == s[j+cnt+1])cnt+=2;
else break;
dp[i]=cnt;
cnt=1;
for(int j=i-1;j>=0 && j+cnt+1<s.size();j--)
if(s[j] == s[j+cnt+1])cnt+=2;
else break;
//cout << i << " " << j << "*" << cnt << endl;
if(cnt > dp[i])dp[i]=cnt;
//cout << i << " " << j << "*" << cnt << endl;
else
cnt=1;
for(int j=i-1;j>=0 && j+cnt+1<s.size();j--)
if(s[j] == s[j+cnt+1])cnt+=2;
else break;
dp[i]=cnt;
if(dp[i]>mx)
/*if(flag)
st = i-dp[i]/2+1;
else
st = i-dp[i]/2;
*/
st = i-(dp[i]+1)/2+1;
mx = dp[i];
else
dp[i]=1;
//mx = max(mx, dp[i]);
//cout << st << " " << mx << endl;
return s.substr(st,mx);
;
int main()
freopen("5in.txt","r",stdin);
string s;
Solution so;
while(cin >> s)
cout << so.longestPalindrome(s) << endl;
return 0;
以上是关于LeetCode OJ 5 Longest Palindromic Substring的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode OJ 14Longest Common Prefix
Longest Substring Without Repeating Characters -- LeetCode
5. 最长镜像子串 [leetcode 5: Longest Palindromic Substring]
5. 最长镜像子串 [leetcode 5: Longest Palindromic Substring]