文章目录

原题

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.

原题链接:https://leetcode.com/problems/valid-palindrome/description/

代码

C++

[code lang=”cpp”]
class Solution {
public:
bool isPalindrome(string s) {
if (s.length() == 0) return true;
// filter
string fs;
for (int i = 0; i < s.length(); ++i) {
if ((48 <= s[i] && s[i] <= 57) || (65 <= s[i] && s[i] <= 90) || (97 <= s[i] && s[i] <= 122)) {
if (65 <= s[i] && s[i] <= 90) s[i] = tolower(s[i]);
fs.append(s, i, 1);
}
}

int fsl = fs.length();
for (int i = 0; i < fsl / 2; ++i)
if (fs[i] – fs[fsl – i – 1] != 0) return false;

return true;
}
};
[/code]

Python

[code lang=”python”]
import re
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = re.sub(‘[^A-Za-z0-9]’, ”, s).lower()
return s == s[::-1]
[/code]


原文链接:胡小旭 => 2018LeeCode算法题解一之Valid Palindrome

Share:

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.