leetcode-125:验证回文串

简介: leetcode-125:验证回文串

题目

题目链接

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

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

示例 1:

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

示例 2:

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

解题:

方法一:筛选 + 判断

class Solution:
    def isPalindrome(self, s: str) -> bool:
        sgood = "".join(ch.lower() for ch in s if ch.isalnum())
        return sgood == sgood[::-1]

方法二:在原字符串上直接判断

我们直接在原字符串 ss 上使用双指针。在移动任意一个指针时,需要不断地向另一指针的方向移动,直到遇到一个字母或数字字符,或者两指针重合为止。也就是说,我们每次将指针移到下一个字母字符或数字字符,再判断这两个指针指向的字符是否相同。

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

这些方法都使用了isalnum()方法,如果不用这个就需要用到ord()转为ASCII码,用chr()把ASCII码转为字符,手动转为小写和数字。

相关文章
|
1月前
|
存储 canal 算法
[Java·算法·简单] LeetCode 125. 验证回文串 详细解读
[Java·算法·简单] LeetCode 125. 验证回文串 详细解读
23 0
|
3月前
|
Go
golang力扣leetcode 132.分割回文串II
golang力扣leetcode 132.分割回文串II
26 0
|
3月前
|
Go
golang力扣leetcode 98. 验证二叉搜索树
golang力扣leetcode 98. 验证二叉搜索树
15 0
|
3月前
|
存储 算法 C++
leetcode131分割回文串刷题打卡
leetcode131分割回文串刷题打卡
20 0
|
3月前
|
测试技术
leetcode98验证二叉搜索树刷题打卡
leetcode98验证二叉搜索树刷题打卡
18 0
|
3月前
|
Java
leetcode-131:分割回文串
leetcode-131:分割回文串
20 1
|
3月前
|
C++ Python
leetcode-98:验证二叉搜索树
leetcode-98:验证二叉搜索树
32 1
|
4月前
|
算法 vr&ar 图形学
☆打卡算法☆LeetCode 214. 最短回文串 算法解析
☆打卡算法☆LeetCode 214. 最短回文串 算法解析
|
4月前
|
算法 vr&ar 图形学
☆打卡算法☆LeetCode 132. 分割回文串 II 算法解析
☆打卡算法☆LeetCode 132. 分割回文串 II 算法解析
LeetCode刷题Day16——二叉搜索树(搜索、验证、最小绝对差、众数)
一、二叉搜索树中的搜索 题目链接:700. 二叉搜索树中的搜索

热门文章

最新文章