125. Valid Palindrome
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: “A man, a plan, a canal: Panama”
Output: true
Example 2:
Input: “race a car”
Output: false
思路:遍历字符串,去掉非字母数字的,倒序检查是否相等
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
plaindrome = list(s)
newstr = ""
for i in plaindrome:
if i.isalnum():
i = i.lower()
newstr+=i
return newstr==newstr[::-1]
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
i = -1
j = len(s)
while True:
i += 1
j -= 1
if i > j:
return True
while i < j:
if not s[i].isalnum():
i += 1
else:
break
while i < j:
if not s[j].isalnum():
j -= 1
else:
break
if s[i].lower() != s[j].lower():
return False
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
cleanlist = [c for c in s.lower() if c.isalnum()]
return cleanlist == cleanlist[::-1]
请多多指教。
文章标题:125. Valid Palindrome
本文作者:顺强
发布时间:2019-10-16, 23:59:00
原始链接:http://shunqiang.ml/leetcode-125-valid-palindrome/版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。