正确解法
class Solution(object):
def validPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
# Note(3) 判断是否是严格意义上的回文的子函数
def isPalindrome(s):
i, j = 0, len(s)-1
while i < j:
if s[i] == s[j]:
i = i + 1
j = j - 1
else:
return False
return True
i, j = 0, len(s)-1
while i<j:
if s[i] == s[j]:
i = i + 1
j = j - 1
else:
if isPalindrome(s[(i+1):(j+1)]):
# Note(1)如果删除左侧字符后剩下的字符串,是严格的回文(不能删除任何一个字符的)
return True
elif isPalindrome(s[i:j]):
# Note(2)如果删除右侧字符后剩下的字符串,是严格的回文(不能删除任何一个字符的)
return True
else:
return False
return True
完全是一个贪心算法哈~Note(1)(2)(3)是三个关键的地方
详细的图解请见:
https://leetcode-cn.com/problems/valid-palindrome-ii/
正确解法:优化代码
class Solution:
def validPalindrome(self, s: str) -> bool:
def checkPalindrome(low, high):
i, j = low, high
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
low, high = 0, len(s) - 1
while low < high:
if s[low] == s[high]:
low += 1
high -= 1
else:
return checkPalindrome(low + 1, high) or checkPalindrome(low, high - 1)
return True
参考题解:https://leetcode.cn/problems/valid-palindrome-ii/solutions/251842/yan-zheng-hui-wen-zi-fu-chuan-ii-by-leetcode-solut/
错误解法没有看出来为什么错误?
双指针,分别从头和尾开始,如果s[i]不等于s[j]的时候,i++或者j–之后继续比较剩余的部分
也就是判断比较s[i++,j]或者s[i,j-1]部分是否是字符串
class Solution:
def validPalindrome(self, s: str) -> bool:
i = 0
j = len(s) - 1
flag = 0
while i <= j:
if s[i] == s[j]:
i += 1
j -= 1
else:
if flag != 0:
return False
else:
if (i+1) <= j and s[i+1] == s[j]:
i = i + 2
j = j - 1
flag = 1
elif i <= (j-1) and s[i] == s[j-1]:
i = i + 1
j = j -2
flag = 1
else:
return False
return True