简繁EN

LeetCodeNo. 038

【LeetCode with Python】 125. Valid Palindrome

目錄

題目

原題頁面:https://leetcode.com/problems/valid-palindrome/
題目型別:Two Pointers, String
難度評價:Easy
類似題目:(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.


分析

判斷一個字串是否為迴文,忽略字母和數字外的字元,忽略字母大小寫,並且注意檢測作為引數傳入的字串是否為空串。這可能就是面試時的程式設計題與ACM賽題的最大區別之一:需要考慮各種異常情形和邊界條件,題目雖簡單,面試官考察的是應試者整體的程式設計思維,而不僅僅是具體某個精妙的演算法。


程式碼

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

本文地址:https://xnerv.wang/zh-tw/leetcode-valid-palindrome/