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

leetcode - Longest Palindromic Substring

时间:2015-08-17 00:58:54      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

leetcode - Longest Palindromic Substring

 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) {
        string res;
        int posSubStrBegin=0, posSubStrEnd=0;
        int posTemp = 0;
        int subStrLength = 1;
        int subStrL;
        while(posTemp != s.length()-1 ){
            int posTempHead, posTempTail;
            if(s[posTemp] == s[posTemp+1]){
                posTempHead = posTemp;
                posTempTail = posTemp+1;
                subStrL = 0;
                while(posTempHead >= 0 && posTempTail <= s.length()-1 
                        && s[posTempHead] == s[posTempTail] ){
                    posTempHead--;
                    posTempTail++;
                    subStrL+=2;
                } 
                if(subStrL>subStrLength){
                    posSubStrBegin = posTempHead+1;
                    posSubStrEnd = posTempTail-1;
                    subStrLength = subStrL;
                }
            }
           
            if(posTemp != 0 && s[posTemp-1] == s[posTemp+1]){
                posTempHead = posTemp-1;
                posTempTail = posTemp+1;
                subStrL = 1;
                while(posTempHead >= 0 && posTempTail <= s.length()-1 
                        && s[posTempHead] == s[posTempTail] ){
                    posTempHead--;
                    posTempTail++;
                    subStrL+=2;
                }
                if(subStrL>subStrLength){
                    posSubStrBegin = posTempHead+1;
                    posSubStrEnd = posTempTail-1;
                    subStrLength = subStrL;
                }
            }
           
            posTemp++;
            
        }
        res.assign(s, posSubStrBegin, subStrLength);
        return res;
    }
};

 

leetcode - Longest Palindromic Substring

标签:

原文地址:http://www.cnblogs.com/shnj/p/4735314.html

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