Leetcode 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
题目大意:
判断字符串是否回文,仅考虑字母和数字,并忽略字母大小写。
字符串如何回文,什么是回文?
如果一个字符串,从左右来读都一样,就称它为回文
举个例子:
ABBA
就用最直观地方法,摘选出来列表中的字母和数字,然后再首位对比。
上代码。
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
result = []
for i in s:
if i.isalnum(): #摘选出数字和字母
result.append(i.lower()) #全部转换成小写
length = len(result)
for i in range(0, length//2): #这里得用地板除
if result[i] != result[length-i-1]:
return False
return True
isalnum()方法:
str.isalnum()
如果 string 至少有一个字符并且所有字符都是字母或数字则返回 True,否则返回 False
str = "this2009"; # 字符中没有空格
print str.isalnum();
str = "this is string example....wow!!!";
print str.isalnum();
输出:
True
False
06/05/2020
疫情中的英国,
加油!