forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
valid-palindrome.cpp
44 lines (42 loc) · 1000 Bytes
/
valid-palindrome.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
// Time: O(n)
// Space: O(1)
class Solution {
public:
bool isPalindrome(string s) {
int i = 0, j = s.length() - 1;
while (i < j) {
if (!isalnum(s[i])) {
++i;
} else if (!isalnum(s[j])) {
--j;
} else if (tolower(s[i]) != tolower(s[j])) {
return false;
} else {
++i, --j;
}
}
return true;
}
};
// Time: O(n)
// Space: O(1)
// Iterator solution.
class Solution2 {
public:
bool isPalindrome(string s) {
auto left = s.begin();
auto right = prev(s.end());
while (left < right) {
if (!isalnum(*left)) {
++left;
} else if (!isalnum(*right)) {
--right;
} else if (tolower(*left) != tolower(*right)) {
return false;
} else {
++left, --right;
}
}
return true;
}
};