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

Leetcode 5. Longest Palindromic Substring

时间:2016-06-25 23:05:59      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

5. Longest Palindromic Substring

Total Accepted: 115366 Total Submissions: 492202 Difficulty: Medium

 

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.

 

技术分享
class Solution {
public:
    string longestPalindrome(string s) {
        if(s.length()<2) return s;
        int i,left,right,maxlen=0,tleft;
        for(i=0;i<s.length();){
            if(s.length()-i<=maxlen/2) break;
            left=right=i;
            while(right<s.length()-1&&s[right+1]==s[right]) right++;
            i=right+1;
            while(left>0&&right<s.length()-1&&s[left-1]==s[right+1]){left--;right++;}
            if(right-left+1>maxlen){
               maxlen=right-left+1;
               tleft=left;
            }
        }
        return s.substr(tleft,maxlen);
    }
};
View Code

 

Leetcode 5. Longest Palindromic Substring

标签:

原文地址:http://www.cnblogs.com/Deribs4/p/5617009.html

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