-
Notifications
You must be signed in to change notification settings - Fork 1
/
125.cpp
51 lines (42 loc) · 1.13 KB
/
125.cpp
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
// 125. Valid Palindrome - https://leetcode.com/problems/valid-palindrome
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool is_alphanumeric(char ch) {
return ('0' <= ch && ch <= '9') ||
('a' <= tolower(ch) && tolower(ch) <= 'z');
}
bool isPalindrome(string s) {
int left = 0;
int right = s.length() - 1;
for (char & ch : s) {
if ('A' <= ch && ch <= 'Z') {
ch = tolower(ch);
}
}
while (left < right) {
if (!is_alphanumeric(s[left])) {
++left;
continue;
}
if (!is_alphanumeric(s[right])) {
--right;
continue;
}
if (s[left] != s[right]) {
return false;
}
++left;
--right;
}
return true;
}
};
int main() {
ios::sync_with_stdio(false);
Solution solution;
assert(solution.isPalindrome("A man, a plan, a canal: Panama") == true);
assert(solution.isPalindrome("race a car") == false);
return 0;
}