Leetcode 5. 最长回文子串 Manacher

题意:求出一个字符串的最长回文子串,如"babad"输入“bab”
思路:首先可以枚举每个点,以该点为中心扩展,取扩展半径最大的为答案。由于偶数长度串中心为两个点,故可以在两点间插入一个任意字符使得不管奇数偶数串都变为奇数串来处理

class Solution {
public:
    string longestPalindrome(string s) {
        int maxx = 0;
        string s2 = "#", res = "", ans = "";
        if (s.length() == 1)
            return s;
        int t = s.length();
        for (int i = 0; i < s.length(); i++) {
            s2 = s2 + s[i] + "#";
        }
        for(int i = 1; i < s2.length(); i++) {
            for (int j = 1; i-j >= 0 && i+j < s2.length(); j++) {
                if (s2[i-j] == s2[i+j]) {
                    if (j > maxx) {
                        maxx = j;
                        res = s2.substr(i-j, j*2+1);
                    }
                } else {
                    break;
                }
            }
        }
        for (int i = 0; i < res.length(); i++)
            if (res[i] != '#')
                ans = ans + res[i];  
        return ans;
    }
};

最长回文子串的典型解决算法是Manacher,即优化过后的中心扩展法,根据对称点防止匹配失败后返回起始点从头开始匹配

class Solution {
public:
    string longestPalindrome(string s) {
        int maxx = 0, flag = 0, ans = 0;
        string s2 = "$#", res = "", res2 = "";
        for (int i = 0; i < s.length(); i++) {
            s2 = s2 + s[i] + "#";
        }
        int cnt[s2.length()];
        for(int i = 0; i < s2.length(); i++) {
            cnt[i] = maxx > i ? min(cnt[2*flag-i], maxx-i) : 1;
            while (i+cnt[i] < s2.length() && i-cnt[i] >= 0 && s2[i+cnt[i]] == s2[i-cnt[i]]) {
                cnt[i]++;
            }
            if (i + cnt[i] > maxx) {
                maxx = i + cnt[i];
                flag = i;
            }
            if (cnt[i] > ans && i-cnt[i] >= 0) {
                ans = cnt[i];
                res = s2.substr(i-cnt[i]+1, (cnt[i]-1)*2+1);
            }
            }
            for (int i = 0; i < res.length(); i++) {
                if (res[i] != '#')
                    res2 = res2 + res[i];
            } 
            return res2;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值