Leetcode——125 验证回文串

LeetCode125题目

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

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

示例 1:

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

输入: “race a car”
输出: false

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-palindrome

方法一:python内置函数

class Solution:
    def isPalindrome(self, s: str) -> bool:
        s_filter = ' '.join(filter(str.isalnum, s)).lower()
        return s_filter[::-1] == s_filter

Python isalnum() 方法

Python isalnum() 方法检测字符串是否由字母和数字组成。使用方法:str.isalnum()
参考链接https://www.runoob.com/python/att-string-isalnum.html

filter() 函数

filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换。

该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。

filter(function, iterable)

参考链接:https://www.runoob.com/python3/python3-func-filter.html

.join()函数

. join(): 连接字符串数组。将字符串、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串
’ '.join()以空格分开
‘,’.join()以逗号分开

参考链接:https://www.cnblogs.com/ling-yu/p/9167065.html

列表[: : -1]

b = a[i:j:s]
表示:复制a[i]到a[j-1],以生成新的list对象,但s表示步进,缺省为1。所以a[i:j:1]相当于a[i:j]
当s<0时,i缺省时,默认为-1. j缺省时,默认为-len(a)-1
#所以a[::-1]相当于 a[-1:-len(a)-1:-1],也就是从最后一个元素到第一个元素复制一遍,即倒序。

参考链接:https://www.cnblogs.com/neozheng/p/11219867.html

方法二:双指针法(碰撞指针)

错误解法

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

修正:

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

另一种写法:

class Solution:
 def isPalindrome(self, s: str) -> bool:
     left = 0
     right = len(s)-1
     while left < right:
         if not s[left].isalnum():
             left += 1 
             continue
         if not s[right].isalnum():
             right -= 1
             continue
         if s[left].lower() != s[right].lower():
             return False
         else:
             left += 1
             right -= 1
     return True
发布了6 篇原创文章 · 获赞 0 · 访问量 58

猜你喜欢

转载自blog.csdn.net/qq_35493320/article/details/104281767