[Leetcode]Longest Palindromic Substring

Longest Palindromic Substring
Total Accepted: 82394 Total Submissions: 381112 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.

Subscribe to see which companies asked this question

使用暴力去做算法的时间复杂度肯定是O(n ^2),然后有一种叫做manacher的算法。可以把时间复杂度降到O(n)。详细的资料:戳这里

class Solution {
public:
    string longestPalindrome(string s) {
        int len = s.size();
        if(!len)    return "";
        string str("$");
        for(int i = 0;i <= len - 1;++ i){
            str.push_back('#');
            str.push_back(s[i]);
        }
        str.push_back('#');
        len = str.size();
        int id = 0;
        int maxDis = 0;
        vector<int> p(len,0);
        for(int i = 1;i <= len - 1;++ i){
            if(maxDis > i){
                p[i] = min(maxDis - i,p[2 * id - i]);
            }
            for(;str[i - p[i]] == str[i + p[i]];++ p[i])
                ;
            if(i + p[i] > maxDis){
                id = i;
                maxDis = i + p[i];
            }
        }
        int maxLen = 0;
        int pos = 0;
        for(int i = 0;i <= p.size() - 1;++ i){
            if(p[i] > maxLen){
                maxLen = p[i];
                pos = i;
            }
        }
        string res(str.substr(pos - maxLen + 1,maxLen * 2 - 1));
        string ans;
        for(auto ch : res){
            if(ch != '#'){
                ans.push_back(ch);
            }
        }
        return ans;
    }
};

posted on 2015-12-10 15:17  泉山绿树  阅读(19)  评论(0)    收藏  举报

导航