题目:
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
解释:
判断一个句子是不是回文,去掉标点符号,把句子转换成小写。
不要用replace()
了,因为特殊符号了,判断这个字符是不是alphanumeric然后小写化后加入到一个新的字符串中。
python代码:
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s= [x for x in s.lower() if x.isalnum()]
return s==s[::-1]
c++代码:
#include <string>
#include <cctype>
#include <algorithm>
using namespace std;
class Solution {
public:
bool isPalindrome(string s) {
transform(s.begin(),s.end(),s.begin(),::tolower);
string new_s="";
for (auto letter:s)
{
if (isalnum(letter))
new_s+=letter;
}
string reverse_new_s(new_s);
reverse(reverse_new_s.begin(),reverse_new_s.end());
return new_s==reverse_new_s;
}
};
双指针解法,更加常规的解法,python代码:
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s= [x.lower() for x in s if x.isalnum()]
left=0
right=len(s)-1
while left<right:
if s[left]!=s[right]:
return False
left+=1
right-=1
return True
总结:
<cctype>
里面:
大小写转换:
transform(s.begin(),s.end(),s.begin(),::tolower)
判断是不是字符数字的:
isalnum(c)