描述:给定一个字符串,忽略大小写和标点符号,判断该句子是否是回文
输入:Race e car
输出:不是
思路:因为忽略大小写因此先对整个字符串进行大小写调整,使用toupper(),或者tolower()函数。然后分别在第一个字符和最后一个字符设置迭代器,若两个迭代器都指向数字或者字符则比较。
#include<ctype.h>
#include<algorithm>
class Solution{
public:
bool isPalindrome(string s)
{
transform(s.begin(),s.end(),s.begin(),::tolower);
string::iterator first,last;
first=s.begin();
last=prev(s.end());
while(first<last)
{
if(!::isalnum(*first)first++;
else if(!::isalnun(*last))last--;
else if(*first!=*last) return false;
else {
first++;
last--;
}
}
return true;
}
};
其中,tolower不能直接调用是因为C++<
locale
>和<cctype>中都有tolower,因此需要限定域,另外一个方法是
transform(cbegin(s), cend(s), begin(s), static_cast<int(*)(int)>(tolower));