首页 > 其他 > 详细

Longest Palindromic Substring

时间:2015-09-07 22:48:17      阅读:205      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!