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.

 

 1 class Solution {
 2 public:
 3     string longestPalindrome(string s) {
 4  const int len = s.size();
 5         if(len <= 1)return s;
 6         int start, maxLen = 0;
 7         for(int i = 1; i < len; i++)
 8         {
 9             //寻找以i-1,i为中点偶数长度的回文
10             int low = i-1, high = i;
11             while(low >= 0 && high < len && s[low] == s[high])
12             {
13                 low--;
14                 high++;
15             }
16             if(high - low - 1 > maxLen)
17             {
18                 maxLen = high - low -1;
19                 start = low + 1;
20             }
21              
22             //寻找以i为中心的奇数长度的回文
23             low = i- 1; high = i + 1;
24             while(low >= 0 && high < len && s[low] == s[high])
25             {
26                 low--;
27                 high++;
28             }
29             if(high - low - 1 > maxLen)
30             {
31                 maxLen = high - low -1;
32                 start = low + 1;
33             }
34         }
35         return s.substr(start, maxLen);
36     }
37 
38 };