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

Longest Palindromic Substring

时间:2015-09-07 22:51:12      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:

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 };

 

Longest Palindromic Substring

标签:

原文地址:http://www.cnblogs.com/hexhxy/p/4790118.html

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