码迷,mamicode.com
首页 > 编程语言 > 详细

5. Longest Palindromic Substring(C++)

时间:2017-02-28 18:59:56      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:inpu   length   substring   bst   turn   for   ret   input   stp   

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example:

Input: "babad"

Output: "bab"

Note: "aba" is also a valid answer.

 

Example:

Input: "cbbd"

Output: "bb"

答案:

class Solution {
public:
  string longestPalindrome(string s) {
    if(s.size()<2){
      return s;
    }
    int len = s.size(), maxlen = 1, maxleft = 0, left, right;
    for(int i=0;i<len&&len-i > maxlen/2;){
      left = right = i;
      while(right<len-1 && s[right]==s[right+1]){
        right++;
      }
      i=right+1;
      while(right<len-1 && left>0 && s[left-1]==s[right+1]){
        right++;
        left--;
      }
      if(maxlen<right-left+1){
        maxleft = left;
        maxlen =right-left+1;
      }
    }
    return s.substr(maxleft,maxlen);
  }
};

5. Longest Palindromic Substring(C++)

标签:inpu   length   substring   bst   turn   for   ret   input   stp   

原文地址:http://www.cnblogs.com/devin-guwz/p/6480252.html

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