美文网首页
LeetCode-680-验证回文字符串 Ⅱ

LeetCode-680-验证回文字符串 Ⅱ

作者: 阿凯被注册了 | 来源:发表于2020-11-10 21:29 被阅读0次

    给定一个非空字符串 s,最多删除一个字符。判断是否能成为回文字符串。

    image.png
    解题思路:
    1. 判断是否回文字符串:isPalindrome = lambda x: x==x[::-1],即将字符串x倒置,还和原来的一样;
    2. 如何判断删除一个字符后还是回文字符串?假设字符串s='abccbca',当用双指针从两端向中间游走,如果两指针所指字符不相等,考虑删除其中之一,再判断是否回文字符串。
    3. 该例中当left=1和right=5时,删除其中之一再判断,只需判断left和right之间的字符串是否回文,生成的新的两个字符串分别为删除右边字符:s[left:right],删除左边字符:s[left+1:right+1]

    Python3代码:

    class Solution:
        def validPalindrome(self, s: str) -> bool:
            left = 0
            right = len(s)-1
            isPalindrome = lambda x : x == x[::-1]
    
            while left<=right:
                if s[left] != s[right]:
                    return isPalindrome(s[left:right]) or isPalindrome(s[left+1:right+1])
                else:
                    left+=1
                    right-=1
            return True 
    

    相关文章

      网友评论

          本文标题:LeetCode-680-验证回文字符串 Ⅱ

          本文链接:https://www.haomeiwen.com/subject/ngcsbktx.html