-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path125.验证回文串.py
53 lines (48 loc) · 1.08 KB
/
125.验证回文串.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#
# @lc app=leetcode.cn id=125 lang=python3
#
# [125] 验证回文串
#
# https://leetcode-cn.com/problems/valid-palindrome/description/
#
# algorithms
# Easy (42.34%)
# Likes: 154
# Dislikes: 0
# Total Accepted: 77.6K
# Total Submissions: 183.3K
# Testcase Example: '"A man, a plan, a canal: Panama"'
#
# 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
#
# 说明:本题中,我们将空字符串定义为有效的回文串。
#
# 示例 1:
#
# 输入: "A man, a plan, a canal: Panama"
# 输出: true
#
#
# 示例 2:
#
# 输入: "race a car"
# 输出: false
#
#
#
# @lc code=start
class Solution:
def isPalindrome(self, s: str) -> bool:
# 双指针
l, r = 0, len(s) - 1
while l < r:
while l < r and not s[l].isalnum():
l += 1
while l < r and not s[r].isalnum():
r -= 1
if s[l].lower() != s[r].lower():
return False
l += 1
r -= 1
return True
# @lc code=end