题目描述 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
思路解析 仅考虑字母数字,忽略大小写,首尾相同;
python示例, 两行代码。运行时间48 ms class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ temp = [i for i in s.lower() if i in "0123456789abcdefghijklmnopqrstuvwxyz"] return temp == temp[::-1]2.python示例,使用正则替换。Runtime: 24 ms, faster than 99.71% of Python online submissions for Valid Palindrome.
class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ import re temp = re.sub("\W+", "", s).lower() # \W+ 用于所有与\w+不匹配的其他字符 ,详情见下方 return temp == temp[::-1]附加 正则匹配点 \s:用于匹配单个空格符,包括tab键和换行符; \S:用于匹配除单个空格符之外的所有字符; \d:用于匹配从0到9的数字; \w:用于匹配字母,数字或下划线字符; \W:用于匹配所有与\w不匹配的字符; . :用于匹配除换行符之外的所有字符。
cpp示例。Runtime: 8 ms, faster than 96.25% of C++ online submissions for Valid Palindrome. class Solution { public: bool isPalindrome(string s) { int i = 0; int j = s.size() - 1; while(i < j){ while(i<j && !isAlphaNumeric(s[i])) i++; while(j>i && !isAlphaNumeric(s[j])) j--; if (tolower(s[i]) != tolower(s[j])) return false; i++; j--; } return true; } inline bool isAlphaNumeric(char c) const{ if (c >= 'a' && c <= 'z') return true; else if (c >= 'A' && c <= 'Z') return true; else if (c >= '0' && c <= '9') return true; else return false; } }; cpp示例,简短版本。Runtime: 12 ms, faster than 71.73% of C++ online submissions for Valid Palindrome. class Solution { public: bool isPalindrome(string s) { int i = 0; int j = s.size() - 1; while(i < j){ while(i<j && !isalnum(s[i])) i++; while(j>i && !isalnum(s[j])) j--; if (tolower(s[i++]) != tolower(s[j--])) return false; } return true; } };