-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalid_palindrome.cpp
More file actions
70 lines (52 loc) · 1.96 KB
/
valid_palindrome.cpp
File metadata and controls
70 lines (52 loc) · 1.96 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
125. Valid Palindrome
Time Complexity: O(n)
Space Complexity: O(1) for two-pointer approach, O(n) for filter approach
*/
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;
class Solution {
public:
bool isPalindrome(string s) {
int left = 0;
int right = s.length() - 1;
while (left < right) {
while (left < right && !isalnum(s[left])) {
left++;
}
while (left < right && !isalnum(s[right])) {
right--;
}
if (tolower(s[left]) != tolower(s[right])) {
return false;
}
left++;
right--;
}
return true;
}
};
// Test cases
int main() {
Solution solution;
// Example 1
cout << "Example 1: " << (solution.isPalindrome("A man, a plan, a canal: Panama") ? "true" : "false") << endl; // Expected: true
// Example 2
cout << "Example 2: " << (solution.isPalindrome("race a car") ? "true" : "false") << endl; // Expected: false
// Example 3
cout << "Example 3: " << (solution.isPalindrome(" ") ? "true" : "false") << endl; // Expected: true
// Edge case: empty string
cout << "Example 4: " << (solution.isPalindrome("") ? "true" : "false") << endl; // Expected: true
// Edge case: single character
cout << "Example 5: " << (solution.isPalindrome("a") ? "true" : "false") << endl; // Expected: true
// Edge case: all special characters
cout << "Example 6: " << (solution.isPalindrome(".,!@#") ? "true" : "false") << endl; // Expected: true
// Edge case: with numbers
cout << "Example 7: " << (solution.isPalindrome("0P") ? "true" : "false") << endl; // Expected: false
// Edge case: numbers palindrome
cout << "Example 8: " << (solution.isPalindrome("1a2b2a1") ? "true" : "false") << endl; // Expected: true
return 0;
}