LintCode Q415 Valid Palindrome in Python

  • Jinhai ZHOU
  • 4 Minutes
  • 2016年11月30日
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
class Solution:
# @param {string} s A string
# @return {boolean} Whether the string is a valid palindrome
def isPalindrome(self, s):
# Write your code here
s = s.lower()
head = 0
rear = len(s) - 1
while head < rear:
r1 = self.isAlphanumeric(s[head])
r2 = self.isAlphanumeric(s[rear])
if r1 and (not r2):
rear -= 1
elif (not r1) and r2:
head += 1
elif (not r1) and (not r2):
head += 1
rear -= 1
else:
if s[head] == s[rear]:
head += 1
rear -= 1
else:
return False
return True
def isAlphanumeric(self, char):
c = ord(char)
a = ord('a')
z = ord('z')
zero = ord('0')
nine = ord('9')
if (c >= a and c <= z) or (c >= zero and c <= nine):
return True
else:
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。