码迷,mamicode.com
首页 > 其他好文 > 详细

L2-008. 最长对称子串 (有个知识点没看)

时间:2016-05-15 21:38:16      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:

题目:

思路

方法一:判断字符串的每一个子串,若是对称的,则求出它的长度即可。这种办法对每一个子串,从两头向中间判断是不是子串。总的时间复杂度为O(n^3),

下面给出时间复杂度是O(n^2)的思路。

方法二:与方法一正好相反,字符串中的每一个开始,向两边扩展,此时可分为两种情况:

(1)对称子串长度是奇数时, 以当前字符为对称轴向两边扩展比较

(2)对称子串长度是偶数时,以当前字符和它右边的字符为对称轴向两边扩展

 

技术分享
 1 #include <cstdio>
 2 #include <cstring>
 3 int maxsubstring(char *str)
 4 {
 5     int length=1,newlength,i;
 6     int left,right;
 7     int len=strlen(str);
 8     for(i=0;i<len;i++)
 9     {
10         newlength=1;    //对称可能为奇数时
11         left=i-1;
12         right=i+1;
13         for(;left>=0&&right<len;left--,right++)
14             if(str[left]==str[right])
15                 newlength+=2;
16             else
17                 break;
18         if(newlength>length)
19             length=newlength;
20         
21         newlength=0;    //对称可能为偶数时
22         left=i;
23         right=i+1;
24         for(;left>=0&&right<=len;left--,right++)
25             if(str[left]==str[right])
26                 newlength+=2;
27             else
28                 break;
29         if(newlength>length)
30             length=newlength;
31     }
32     return length;
33 }
34 int main()
35 {
36     char str[1005];
37     gets(str);
38     int ret;
39     ret=maxsubstring(str);
40     printf("%d\n",ret);
41     return 0;
42 }
View Code

 

 

网上说还有个O(n)的 

上网查了下 http://www.cnblogs.com/biyeymyhjob/archive/2012/10/04/2711527.html 

有时间再看看吧。。毕竟速度是遍历的快的多。。。

L2-008. 最长对称子串 (有个知识点没看)

标签:

原文地址:http://www.cnblogs.com/WDKER/p/5496022.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!