红桃J

用心写好每行完美的代码,远比写一堆更有价值

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

优秀的解法:http://www.cnblogs.com/xubenben/p/3330746.html

代码:(Time Limit  Exceeded),这博客已经被我写成我的刷题实况了。接下来还有新的写法。

 1 #include<iostream>
 2 #include<string>
 3 
 4 using namespace std;
 5 
 6 string longestPalindrome(string s)
 7 {
 8     int n = s.length();
 9     int max = n;
10     if (n == 1)
11         return s;
12     while (max != 1)
13     {
14         int i = n - max;
15         int j = 0;
16         while (j <= i)
17         {
18             int t = j;
19             int middle = max / 2 + j - 1;
20             for (; t <= middle; t++)
21             {
22                 if (max % 2 == 1)
23                 {
24                     if (s[t] != s[middle * 2 + 2 - t])
25                     {
26                         break;
27                     }
28                 }
29                 else
30                 {
31                     if (s[t] != s[middle * 2 - t + 1])
32                     {
33                         break;
34                     }
35                 }
36             }
37             if (t == middle + 1)
38             {
39                 return s.substr(j, j+max);
40             }
41             else
42             {
43                 j++;
44             }
45         }
46         max--;
47     }
48 }
49 
50 int main()
51 {
52     string s = "a";
53     cout << s << endl;
54     cout << longestPalindrome(s) << endl;
55 }

 

posted on 2015-03-06 23:06  红桃J  阅读(131)  评论(0编辑  收藏  举报