125. Valid Palindrome
problem
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.
判断一个str是不是回文(无效字符忽略)
难度不高,注意的是空字符 and 数字也算有效字符
- 效率对比:30000的回文字符判断1000次
最初的解法:11.31s
discuss1解法:8.18s
discuss2解法:5.25s
-
wille循环改为strlist == strlist[::-1] 提升1s
-
str.isalnum(object) 比 object.isalnum()要慢
-
str(object)的转换时题目理解错误时使用isalpha需要的,现在冗余
修改下面后达到5.25s
strlist = "".join([x.upper() for x in s if x.isalnum()])
solution
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
strlist = [x.upper() for x in s if str.isalnum(str(x))]
if strlist:
length = len(strlist)/2
i = 0
while i <= length:
if strlist[i] != strlist[-i-1]:
return False
i += 1
return True
discuss1
def isPalindrome(self, s):
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
discuss2
class Solution:
# @param s, a string
# @return a boolean
def isPalindrome(self, s):
s = "".join([c.lower() for c in s if c.isalnum()])
return s == s[::-1]

浙公网安备 33010602011771号