算法升级打怪

LeetCode125-验证回文串-Python实现

2021-06-09  本文已影响0人  羊yang678

题目难度: Easy
题目描述:
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-palindrome/

验证回文串的思路一般有两种:

  1. 字符串反转后和原串相等
  2. 使用两个指针,前后两指针指向的元素相等
    这一题特殊的地方在于只考虑字母和数字字符,不考虑其他字符,如空格,一些特殊字符 ¥ # 等。所以可以考虑先将字符串中的数字、字母摘出来,组成新的字符串,然后采用以上两种方法判断字符串是否是回文字符串。不过这种方法需要额外开辟空间,并非最优解。 另一种思路是采用两个指针的方法,但是指针所指元素如果非字母或字符串,则不进行比较,而是直接将指针向前向后移动。

Python 代码实现:

class Solution:
    def isPalindrome(self, s: str) -> bool:
        if not s:
            return True
        left, right = 0, len(s) - 1
        while left <  right:
            while left<right and not s[left].isalnum():
                left = left + 1
            while left<right and not s[right].isalnum():
                right = right - 1
            if s[left].lower() != s[right].lower():
                return False
            left = left + 1
            right = right - 1
        return True
上一篇 下一篇

猜你喜欢

热点阅读