DAY26:leetcode #5 Longest Palindromic Substring

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example:

Input: "babad"

Output: "bab"

Note: "aba" is also a valid answer.

Example:

Input: "cbbd"

Output: "bb"

Subscribe to see which companies asked this question

class Solution(object):
    def findPalindrome(self, s, index):
        step = 0
        i = index - 1
        j = index + 1
        while i >= 0 and j< len(s):
            if s[i] == s[j]:
                i -= 1
                j += 1
                step += 1
            else:
                break
        return step
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        s_temp = ['#']
        for s_t in s:
            s_temp.append(s_t)
            s_temp.append('#')
        steps = [0]*len(s_temp)
        C = L = R = 0 
        for i in range(len(s_temp)):
            i_l = 2*C - i 
            if i_l < 0 or steps[i_l] >= R - i:
                steps[i] = self.findPalindrome(s_temp, i)
                C = i
                L = i - steps[i]
                R = i + steps[i]
            else:
                steps[i] = steps[i_l]
        m_index = steps.index(max(steps))
        result = []
        L = R = m_index
        i = 0
        while i <= steps[m_index]:
            if L == R:
                if s_temp[L] != '#':
                    result.append(s_temp[L])
            else:
                if s_temp[L] != '#':
                    result.insert(0,s_temp[L])
                if s_temp[R] != '#':
                    result.append(s_temp[R])
            i += 1
            L -= 1
            R += 1
        return ''.join(result)

译文在此: [译+改]最长回文子串(Longest Palindromic Substring) Part II

这道题我采用的思路是Manacher算法,其主要思想先将字符与字符之间插入#号,这样从中间往两边找的时候,就不用奇偶序列分别考虑了。

然后在从前到后遍历的过程中,利用前面的中心轴对称性质,可以简化掉一部分计算。详见链接文章。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值