leetcode算法题基础(七)双指针(三)125 题 验证回文串

给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。

说明:本题中,我们将空字符串定义为有效的回文串。

示例 1:

输入: "A man, a plan, a canal: Panama"
输出: true
示例 2:

输入: "race a car"
输出: false

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-palindrome
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

class Solution:
    def isPalindrome(self, s: str) -> bool:
        # 双指针法
        low = 0
        high = len(s) -1
        while low < high :
            # low是非字母数字,向后走
            while low < high and not s[low].isalnum():
                low +=1
            # high是非字母数字,向前走
            while low < high and not s[high].isalnum():
                high -=1
            # 遇到是字母或者数字的情况
            # 需要字母忽略大小写
            if s[low].upper() != s[high].upper():
                return False
            low += 1
            high -= 1
        return True

注意:
1、只考虑输入字符串中的字母和数字部分(空格,符号字符不考虑)
2、忽略字母的大小写

 

posted @ 2020-11-18 10:18  秋华  阅读(107)  评论(0编辑  收藏  举报