LeetCode Longest Palindromic Substring

来源:互联网 发布:金蝶进销存软件多少钱 编辑:程序博客网 时间:2024/06/06 17:36

题目

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length ofS is 1000, and there exists one unique longest palindromic substring.

 

几种思路:

1、动态规划,如果s[i~j]是,则s[i]=s[j]且s[i+1~j-1]也是,n^2。

2、以每个数、每两个连续的数为中心向两边展开,n^2。

其实暴力扫描也是n^2……

3、网上见到一种很牛的O(n)的方法,http://leetcode.com/2011/11/longest-palindromic-substring-part-ii.html

 

代码:

动态规划的,已经离破时间限制不远了……

class Solution {private:bool flag[1000][1000];//标记s[i~j]是否是回文public:    string longestPalindrome(string s) {if(s.empty())return "";int len=s.size();if(len==1)return s;int i,j;for(i=0;i<len;i++)for(j=0;j<=i;j++)flag[i][j]=true;int max=1;//记录最长长度int begin=0;//对应的起始点int length;for(length=2;length<=len;length++){for(i=0;(j=i+length-1)<len;i++){flag[i][j]=false;if(s[i]==s[j]&&flag[i+1][j-1]==true){flag[i][j]=true;max=length;begin=i;}}}return s.substr(begin,max);    }};


 

0 0