【重来】【vip】5. Longest Palindromic Substring【m】【30】【97】

本文介绍了一种线性时间复杂度的算法来找到给定字符串中的最长回文子串。通过对每次添加字符时可能的最大回文长度进行限制,算法避免了不必要的检查,并通过Python代码实现了这一逻辑。

摘要生成于 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.


Subscribe to see which companies asked this question




注释掉的是n^2的

没注释的是线性的算法

这是discuss里面给的解释
还得再看一遍。。

Basic thought is simple. when you increase s by 1 character, you could only increase maxPalindromeLen by 1 or 2, and that new maxPalindrome includes this new character. Proof: if on adding 1 character, maxPalindromeLen increased by 3 or more, say the new maxPalindromeLen is Q, and the old maxPalindromeLen is P, and Q>=P+3. Then it would mean, even without this new character, there would be a palindromic substring ending in the last character, whose length is at least Q-2. Since Q-2 would be >P, this contradicts the condition that P is the maxPalindromeLen without the additional character.

So, it becomes simple, you only need to scan from beginning to the end, adding one character at a time, keeping track of maxPalindromeLen, and for each added character, you check if the substrings ending with this new character, with length P+1 or P+2, are palindromes, and update accordingly.

Now, this is O(n^2) as taking substrings and checking palindromicity seem O(n) time. We can speed up it by realizing that strings are immutable, and there are memory slicing tricks will help to speed these operations up. comparing string equality with "==" is O(1), and using slicing to substring and reverse is ̶a̶l̶s̶o̶ ̶O̶(̶1̶)̶ ̶(̶n̶o̶t̶ ̶t̶o̶t̶a̶l̶l̶y̶ ̶s̶u̶r̶e̶ ̶a̶b̶o̶u̶t̶ ̶t̶h̶e̶ ̶s̶l̶i̶c̶i̶n̶g̶ ̶t̶h̶o̶u̶g̶h̶.̶ ̶ ̶I̶ ̶t̶h̶i̶n̶k̶ ̶i̶t̶ ̶i̶s̶ ̶O̶(̶1̶)̶,̶ ̶b̶u̶t̶ ̶c̶o̶u̶l̶d̶ ̶n̶o̶t̶ ̶f̶i̶n̶d̶ ̶a̶n̶y̶ ̶s̶o̶l̶i̶d̶ ̶l̶i̶t̶e̶r̶a̶t̶u̶r̶e̶ ̶a̶b̶o̶u̶t̶ ̶i̶t̶.̶ O(n) (thanks to ChuntaoLu). But as slicing is optimized by the interpreter's C code, it should run pretty fast. I'm pretty new to Python. Would appreciate you would give more insights or further optimization.

Thus, here is the O(n) method:




class Solution(object):
    def longestPalindrome(self, s):
        
        if len(s)==0:
            return 0
        maxLen=1
        start=0
        for i in xrange(len(s)):
            print i,s[i],s[start:start+maxLen]
            if i-maxLen >=1 and s[i-maxLen-1:i+1]==s[i-maxLen-1:i+1][::-1]:
                print s[i-maxLen-1:i+1]
                start=i-maxLen-1
                maxLen+=2
                continue

            if i-maxLen >=0 and s[i-maxLen:i+1]==s[i-maxLen:i+1][::-1]:
                start=i-maxLen
                maxLen+=1
        return s[start:start+maxLen]
        
        
        
        '''这是n^2的解法
        def helper(s,l,r):
            while l>= 0 and r< len(s) and s[l] == s[r]:
                l-=1
                r+=1
            return s[l+1:r]
            
            
        maxx = 0
        res = ''
        
        for i in xrange(len(s)):
            tmp = helper(s,i,i)
            if len(tmp) > len(res):
                res = tmp
            tmp = helper(s,i,i+1)
            
            if len(tmp) > len(res):
                res = tmp
        return res
        '''
        
        '''
        for i in xrange(len(s)):
            for j in xrange(len(s)-i -1,maxx,-1):
                #print i,j,s[i:i+j]
                
                #print i,j
                
                if s[i] != s[i+j]:
                    continue
                pos = 0
                while pos <= j/2 and s[i+pos] == s[i+j-pos]:
                    pos += 1
                if pos == j/2 + 1 and maxx < j:
                    res = s[i:i+j+1]
                    maxx = j
                    
                
                t = s[i:i+j]
                tt = t[::-1]
                
                if t == tt:
                    if j > maxx:
                        res = t
                        maxx = max(maxx,j)
                
        return res
        '''
        
        """
        :type s: str
        :rtype: str
        """
        


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值