Note: For the purpose of this problem, we define empty string as valid palindrome.
class Solution {
public:
bool palindrome(string s) {
transform(s.begin(), s.end(), s.begin(), ::tolower);
auto left = s.begin, right = prev(s.end());
while (left < right) {
if (!::isalnum(*left))
++left;
else if (!::isalnum(*right))
--right;
else if (*left != *right)
return false;
}
return true;
}
};
这题目是升级版的回文数,但是它要求忽略标点字符和空格以及大小写后能达到左右字符对称;思路是利用左右两个指针同时检测,如果对应位置不能相同,则不是 回文数。
要点:(1)把大写换成小写字母
tolower() 将大写字母转换为小写字母
transform 负责替换
{
#include <algorithm>
std::transform
(The function allows for the destination range to be the same as one of the input ranges to make transformations in place.)
}
(2)掠过空格和标点符号
(3)从左右遍历字符
prev() 获得匹配元素集合中每个元素紧邻的前一个同胞元素,通过选择器进行筛选是可选的。
Note: For the purpose of this problem, we define empty string as valid palindrome.class Solution {public: bool palindrome(string s) { transform(s.begin(), s.end(), s.begin(), ::tolower); aut...