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?恳请大神可以解答疑惑
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这段英文不难理解, 翻译一下就是
举个例子:
输出
所谓回文, 即得出的子串相对中心字符左右对称