1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
class Solution
{
public:
// 辅助函数:判断字符是否是字母或数字
bool check(char c)
{
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
bool isPalindrome(string s)
{
// 双指针初始化
for (int i = 0, j = s.size() - 1; i < j; ++i, --j)
{
// 左指针跳过非字母数字字符
while (i < j && !check(s[i]))
++ i;
// 右指针跳过非字母数字字符
while (i < j && !check(s[j]))
-- j;
// 比较左右字符(忽略大小写)
if (i < j && ::tolower(s[i]) != ::tolower(s[j]))
return false;
}
return true;
}
};
|