[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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值