题目来源
https://leetcode.com/problems/valid-palindrome/
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.
题意分析
Input: a string
Output: whether the string is valid palindrome
Conditions: 判断是否是回文串,忽略非数字和非字母的字符
题目思路
采用isalnum来判断是否为字母或数字,然后将字符转为小写(题目认为大小写是一样的),然后简单判断是否是回文。
AC代码(Python)
1 class Solution(object): 2 def isPalindrome(self, s): 3 """ 4 :type s: str 5 :rtype: bool 6 """ 7 c = [] 8 for i in s: 9 if i.isalnum(): 10 c.append(i.lower()) 11 for i in range(len(c)/2): 12 if c[i] != c[len(c)-1-i]: 13 return False 14 return True