首页 > 其他 > 详细

Longest Palindromic Substring[leetcode]

时间:2014-12-03 23:13:16      阅读:327      评论: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.

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]

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!