Longest Palindromic Substring[leetcode]

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;
    }
};

 

posted on 2014-12-03 22:35  code#swan  阅读(107)  评论(0)    收藏  举报

导航