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
思路: 两个指针分别指向头尾,依次向中间移动,进行比对 需要解决问题在于不考虑字母大小写怎么实现。
s1 = s.lower(),转化为小写https://blog.csdn.net/kelvinLLL/article/details/63680484 去除空格:s2 = s1.replace(‘ ‘, ‘’)https://blog.csdn.net/depers15/article/details/52223956 【Python】从字符串中提取字母字符串的几种方法:https://blog.csdn.net/sxb0841901116/article/details/78508841 python 字符串中提取出数字https://blog.csdn.net/u010412858/article/details/71747488 ~~~ import re
class Solution(object): def isPalindrome(self, s): “”” :type s: str :rtype: bool “”” s1 = s.lower() #s2 = s1.replace(‘ ‘, ‘’) if len(s) == 0 or len(s) == 1: return True s3 = ‘‘.join(re.split(r’[^A-Za-z0-9]’, s1)) length = len(s3) i = 0 j = length-1 while i < j: if s3[i] == s3[j]: i += 1 j -= 1 else: return False return True
if name == “main”: str0 = “0p,” print(Solution().isPalindrome(str0)) ~~~