leedcode解析—Python3—Longest Palindromic Substring—medium

题目:
Given a string s, return the longest palindromic substring in s.

Example 1:
Input: s = “babad”
Output: “bab”
Note: “aba” is also a valid answer.

Example 2:
Input: s = “cbbd”
Output: “bb”

Example 3:
Input: s = “a”
Output: “a”

Example 4:
Input: s = “ac”
Output: “a”

我的思路:
解法1:利用一个判断是否为回文序列的function,从长度为s到1为止,判断所有s子成员是否为回文序列,如果是,即为最长的答案,程序可以结束。然而该方法复杂度为O(n**3),运行超时

解法2:即如下代码,首先确定回文的中间值,列举完所有情况,即将s的所有元素循环一遍,每个中间值分别有两种回文情况,分别为偶数和奇数回文,两种要分开计算。每个中间值分别从中央开始往边缘判断是否回文,有三种情况终止判断,一是第一对回文不符合,直接停止判断;二是判断到了最后一个值,此时计算回文长度是否最佳,如果是,更新答案;三是遭遇回文不符合,此时计算回文长度是否最佳,如果是更新答案,结束判断。该方法复杂度为O(n**2),成绩Runtime: 1192 ms(beats 51.73%)Memory Usage: 14.4 MB(37.65%)

我的解答:

class Solution:
    def longestPalindrome(self, s: str) -> str:
        # get the first answer, and always freshing to get better one
        max_ans = s[0]
        # find answer by moving the medium of palindrome in s
        for i in range(1,len(s)): 
            # decrease the calculation when s in complex
            if 2*(len(s)-i+1) <= len(max_ans):
                break            
            # situation 1, the palindrome is even
            for j in range(min(i,len(s)-i)):
            # if not palindrome,break
                if s[i] != s[i-1]:
                    break
            # when the calculate met the end of s, get the final answer    
                if min(i,len(s)-i) == j+1 and len(max_ans) < len(s[i-1-j:i+1+j]) and s[i+j] == s[i-1-j]:
                    max_ans = s[i-1-j:i+1+j]
            # when the palindrome end, get the final answer
                if s[i+j] != s[i-1-j]:
                    if 2*j > len(max_ans):
                        max_ans = s[i-j:i+j]
                    break
            # situation 2, the palindrome is odd
            for k in range(min(i,len(s)-i-1)):                
                if s[i-1] != s[i+1]:
                    break
                if min(i,len(s)-i-1) == k+1 and len(max_ans) < len(s[i-k-1:i+k+2]) and s[i-k-1] == s[i+1+k]:
                    max_ans = s[i-k-1:i+k+2]
                if s[i-k-1] != s[i+1+k]:
                    if 2*k + 1 > len(max_ans):
                        max_ans = s[i-k:i+k+1]
                    break
        return max_ans

正确的答案合集:
A1:对比s和它的reverse s’,相同的片段即为回文. O(n**2)

A2:同解法1。O(n**3)

A3:优化A2,列举出所有的最短回文,即长度2或3,判断每个最短回文往外扩展一轮是否仍然是回文,如否停止判断,更新最佳答案。O(n**2)

A4:同解法2。O(n**2)

A5(最优解): Manacher’s algorithm
为了同时计算奇偶回文,在字符串s的每个元素中间插入符号"#",分别计算每个元素的最长回文序列,只有自己的话为1,将每个元素的回文序列长度记录于一个新的列表中,再导出最长回文序列的字符串。 O(n)

i       0 1 2 3 4 5 6 7 8 9 10 11 12
arr[i]  # c # a # b # b # a #  f  #
p[i]    1 2 1 2 1 2 5 2 1 2 1  2  1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值