#200 Longest Palindromic Substring

本文介绍了一种高效算法来找到给定字符串中的最长回文子串。通过在字符间插入特殊符号,将问题简化为查找奇数长度的回文子串,最终实现了O(n)时间复杂度的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

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.

Example

Given the string = "abcdzdcab", return "cdzdc".

Challenge 

O(n2) time is acceptable. Can you do it in O(n) time.

题目思路:

这题我打算对于每个ch,都以它为中心看看能得到的palindromic有多长,然后取最长的那个substr。这里有一个trick:由于string length有odd和even之分,如果以一个ch为中心,得到的string就会总是奇数长度;那如果以两个ch为中心,算起来就比较麻烦了。所以,这里在string的两边和每个ch中间都插入‘#’,这样把整个string都转化成一个奇数长度的string,并且保证它的palindromic性质不变,就很容易处理了。

得到substr以后,再把‘#’从中删去,就是我们想要的答案了。

Mycode(AC = 43ms):

class Solution {
public:
    /**
     * @param s input string
     * @return the longest palindromic substring
     */
    string longestPalindrome(string& s) {
        // Write your code here
        // insert '#' in between each char in s
        int idx = 0, max_length = 1;
        string ext = "#";
        while (idx < s.length()) {
            ext += s[idx++];
            ext += "#";
        }
        
        // find the longest palindromic for each i
        // with i as center of the palindromic
        string substr = "";
        for (int i = 1; i < ext.length(); i++) {
            int count = 0;
            string tmp = "";
            while (i - count >= 0 && i + count < ext.length() &&
                   ext[i - count] == ext[i + count])
            {
                tmp = ext.substr(i - count, 1 + 2 * count);
                count++;
            }
            
            max_length = max(max_length, (int)tmp.length());
            substr = tmp.length() == max_length? tmp : substr;
        }
        
        // remove '#' in the substr, that's the answer
        string ans = "";
        for (int i = 0; i < substr.length(); i++) {
            if (substr[i] != '#') {
                ans += substr[i];
            }
        }
        
        return ans;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值