-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path125_Valid Palindrome.cpp
More file actions
50 lines (43 loc) · 1.36 KB
/
125_Valid Palindrome.cpp
File metadata and controls
50 lines (43 loc) · 1.36 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
// Given a string, determine if it is a palindrome, considering only alphanumeric characters
// and ignoring cases.
// For example,
// "A man, a plan, a canal: Panama" is a palindrome.
// "race a car" is not a palindrome.
// 解法:首尾两指针向中间扫描,用isalnum判断是否需跳过当前字符
// 感想:记住一些常用函数所在的库名,tolower函数如果不是字符就会返回原字符
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
class Solution {
public:
bool isPalindrome(string s) {
if (s.size() == 0) return true;
unsigned int forward_itr = 0, backward_itr = s.size() - 1;
bool is_palindrome = true;
// two pointers
while (forward_itr < backward_itr) {
// the cases when they are not alphanumeric chars
if (!isalnum(s[forward_itr])) {
++forward_itr; continue;
} else if (!isalnum(s[backward_itr])) {
--backward_itr; continue;
}
// the cases when they are both alphanumeric chars
if (tolower(s[forward_itr]) == tolower(s[backward_itr])) {
++forward_itr; --backward_itr;
} else {
is_palindrome = false; break;
}
}
// final result
return is_palindrome;
}
};
int main() {
Solution sol;
cout << sol.isPalindrome("A man, a plan, a canal: Panama") << endl;
cout << sol.isPalindrome(" :,") << endl;
cout << sol.isPalindrome(" ad gd ") << endl;
return 0;
}