简繁EN

LeetCodeNo. 038

[LeetCode with Python] 125. Valid Palindrome

Contents

Problem

Problem page: https://leetcode.com/problems/valid-palindrome/
Topics: Two Pointers, String
Difficulty: Easy
Similar problems: (E) Palindrome Linked List

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.

Note:
Have you consider that the string might be empty? This is a good question to > ask during an interview.

For the purpose of this problem, we define empty string as valid palindrome.


Analysis

Check whether the string is a palindrome. Only letters and digits count, and case doesn't matter. Don't forget to check whether the string passed in is empty. This might be one of the biggest differences between interview coding questions and ACM contest problems: you have to think about all sorts of unusual cases and check what happens at the boundaries. It's a simple problem. The interviewer is looking at how the candidate approaches programming as a whole. Knowing a particular clever algorithm is only part of that.


Code

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
class Solution:

# @param s, a string
# @return a boolean
def isPalindrome(self, s):
len_s = len(s)
if len_s <= 1:
return True

left_idx = 0
right_idx = len_s - 1
is_match = True
while left_idx < right_idx:

if (False == ((s[left_idx] >= 'a' and s[left_idx] <= 'z') or (s[left_idx] >= 'A' and s[left_idx] <= 'Z')\
or (s[left_idx] >= '0' and s[left_idx] <= '9'))):
left_idx += 1
continue
left_chr = (chr(ord(s[left_idx]) - ord('A') + ord('a'))\
if (s[left_idx] >= 'A' and s[left_idx] <= 'Z') else s[left_idx])

if (False == ((s[right_idx] >= 'a' and s[right_idx] <= 'z') or (s[right_idx] >= 'A' and s[right_idx] <= 'Z')\
or (s[right_idx] >= '0' and s[right_idx] <= '9'))):
right_idx -= 1
continue
right_chr = (chr(ord(s[right_idx]) - ord('A') + ord('a'))\
if (s[right_idx] >= 'A' and s[right_idx] <= 'Z') else s[right_idx])

if left_chr == right_chr:
left_idx += 1
right_idx -= 1
else:
is_match = False
break

return is_match

Article link: https://xnerv.wang/en/leetcode-valid-palindrome/