python最长回文子串leetcode_Leetcode最长回文子串问题

LeetCode第五题,最长回文子串问题,其中Python下面有一种解法,原理有点看不懂,英文描述如下:

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.

下面是代码:

class Solution:

# @return a string

def longestPalindrome(self, s):

if len(s)==0:

return 0

maxLen=1

start=0

for i in xrange(len(s)):

if i-maxLen >=1 and s[i-maxLen-1:i+1]==s[i-maxLen-1:i+1][::-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]

我主要是不明白他的反证法,特别是这个

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.

这里非常困惑,为什么没有这个新字符,它会有以,前一个字符结尾的最长子串,还有为什么是Q-2?恳请大神可以解答疑惑

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值