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

Longest Palindromic Substring[leetcode]

时间:2014-12-03 23:15:35      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   sp   for   on   div   log   

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) {
        int len = s.length();
        string ans = "";
        for(int i=0;i<len;i++){
            int ind = min(i, len-i-1), j=1;
            for(j=1;j<=ind;j++){
                if(s[i-j] != s[i+j]){
                    break;
                }
            }
            string tmp = s.substr(i-j+1, 2*j-1);
            if(tmp.length() > ans.length())
                ans = tmp;
        }
// assume the length is odd
        for(int i=0;i<len-1;i++){
            if(s[i]==s[i+1]){
                int ind = min(i, len-i-2), j=1;
                for(j=1;j<=ind;j++){
                    if(s[i-j] != s[i+1+j]){
                        break;
                    }
                }
                string tmp = s.substr(i-j+1, 2*j);
                if(tmp.length() > ans.length())
                    ans = tmp;
            }
        }
//assume the length is even
        return ans;
    }
};

 

Longest Palindromic Substring[leetcode]

标签:style   blog   io   color   sp   for   on   div   log   

原文地址:http://www.cnblogs.com/code-swan/p/4141319.html

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