Given a string
S
, find the longest palindromic substring in
S
. You may assume that the maximum length of
S
is 1000, and there exists one unique longest palindromic substring.
首先我用了DP,没想到存储没报错,时间报错了,TLE了。
原理是记录所有回文,然后更新最大值。
比较值得注意的是
后来发现其实朴素的判断回文空间复杂性更小。其实就是从0到n-1遍历,每个节点为中心判断回文,分为奇偶两种情况,
奇数遍历:
偶 数遍历:
代码如下:
首先我用了DP,没想到存储没报错,时间报错了,TLE了。
原理是记录所有回文,然后更新最大值。
比较值得注意的是
- for(int i=n-2;i>=0;i--){
- for(int j=i+1;j<=n-1;j++){
- dp[i][j]=dp[i+1][j-1]&&(s[i]==s[j]);
- string longestPalindrome(string s) {
- int n=s.length();
- vector<vector<bool>> dp(n,vector<bool>(n,false));
- for(int i=0;i<n;i++){
- for(int j=0;j<=i;j++){
- dp[i][j]=true;
- }
- }
- int num=1;
- int x=0;
- int y=0;
- for(int i=n-2;i>=0;i--){
- for(int j=i+1;j<=n-1;j++){
- dp[i][j]=dp[i+1][j-1]&&(s[i]==s[j]);
- if(dp[i][j] && (j-i+1>num)){
- num=j-i+1;
- x=i;
- y=j;
- }
- }
- }
- return s.substr(x,num);
- }
奇数遍历:
- for (int i = 1; i < s.length(); ++i){
- low = i - 1;
- high = i + 1;
- while (low >= 0 && high <s.length() && s[low] == s[high])
- {
- //是回文
- --low;
- ++high;
- }
- }
偶 数遍历:
- for (int i = 1; i < s.length(); ++i){
- low = i - 1;
- high = i;
- while (low >= 0 && high <s.length() && s[low] == s[high])
- {
- //是回文
- --low;
- ++high;
- }
- }
代码如下:
- string longestPalindrome(string s) {
-
- int start = 0;
- int maxLength = 1;
- string res;
-
- if(s.length()==1)
- return s;
- int low, high;
- for (int i = 1; i < s.length(); ++i)
- {
- low = i - 1;
- high = i;
- while (low >= 0 && high < s.length() && s[low] == s[high])
- {
- if (high - low + 1 > maxLength)
- {
- start = low;
- maxLength = high - low + 1;
- }
- --low;
- ++high;
- }
- low = i - 1;
- high = i + 1;
- while (low >= 0 && high <s.length() && s[low] == s[high])
- {
- if (high - low + 1 > maxLength)
- {
- start = low;
- maxLength = high - low + 1;
- }
- --low;
- ++high;
- }
- }
- res = s.substr(start,maxLength);
- return res;
-
-
- }
<script>window._bd_share_config={"common":{"bdsnskey":{},"bdtext":"","bdmini":"2","bdminilist":false,"bdpic":"","bdstyle":"0","bdsize":"16"},"share":{}};with(document)0[(getelementsbytagname('head')[0]||body).appendchild(createelement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new date()/36e5)];</script>
阅读(4) | 评论(0) | 转发(0) |
相关热门文章
给主人留下些什么吧!~~
评论热议
寻找最长回文子串
本文探讨了寻找字符串中最长回文子串的有效算法。首先介绍了动态规划方法,并讨论了其时间复杂度问题。随后提出了一种朴素的方法,通过遍历每个字符作为中心来判断回文,适用于奇数和偶数长度的子串。
601

被折叠的 条评论
为什么被折叠?



