-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path18.cpp
More file actions
executable file
·56 lines (53 loc) · 1.53 KB
/
Copy path18.cpp
File metadata and controls
executable file
·56 lines (53 loc) · 1.53 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
@filename 18.cpp
@author caonan
@date 2022-03-31 15:07:30
@reference 剑指offer专项
@url https://leetcode-cn.com/problems/XltzEq/
@brief 给定一个字符串 s ,验证 s 是否是 回文串 ,只考虑字母和数字字符,可以忽略字母的大小写。
本题中,将空字符串定义为有效的 回文串
*/
#include <assert.h>
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <map>
#include <vector>
using namespace std;
class Solution
{
public:
bool isPalindrome(string s)
{
int left = 0;
int right = s.length() - 1;
auto isLetterOrDig = [](char c) -> bool {
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9') return true;
return false;
};
while (left < right) {
while (left < s.length() && !isLetterOrDig(s[left])) {
left++;
}
while (right >= 0 && !isLetterOrDig(s[right])) {
right--;
}
if (left < right && std::tolower(s[left++]) != std::tolower(s[right--])) {
return false;
}
}
return true;
}
};
int main()
{
Solution s;
assert(s.isPalindrome("abcba"));
assert(!s.isPalindrome("abcb"));
assert(s.isPalindrome("amanaplanacanalpanama"));
assert(s.isPalindrome("A man, a plan, a canal: Panama"));
assert(!s.isPalindrome("race a car"));
assert(s.isPalindrome(""));
assert(s.isPalindrome(" "));
return 0;
}