O(n2):

 1 class Solution {
 2 public:
 3     string getP(string s, int start, int end) {
 4         while (start >= 0 && end < s.size() && s[start] == s[end]) {
 5             start--;
 6             end++;
 7         }
 8         return s.substr(start+1, end - start - 1);
 9     }
10     string longestPalindrome(string s) {
11         int len = s.size();
12         if (len < 2) return s;
13         string result = s.substr(0, 1);
14         for (int i = 0; i < len-1; i++) {
15             string s1 = getP(s, i, i);
16             if (s1.size() > result.size()) result = s1;
17             string s2 = getP(s, i, i+1);
18             if (s2.size() > result.size()) result = s2;
19         }
20         return result;
21     }
22 };

 

TBA (O(n))

posted on 2015-03-20 07:33  keepshuatishuati  阅读(106)  评论(0编辑  收藏  举报