Leetcode 125. Valid Palindrome
The given problem is from LeetCode, and it’s numbered 125. The problem statement is as follows:
Given a string s
, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example:
s = "A man, a plan, a canal: Panama"
Output: true
s = "race a car"
false
left
) and the other from the end (right
).left
and right
indices, and move the pointers towards the center.left
and right
indices do not match, return false
.true
.#include <iostream>
#include <string>
#include <cctype> // for isalnum and tolower
class Solution {
public:
bool isPalindrome(std::string s) {
std::string cleaned;
// Build the cleaned version of the string
for (char c : s) {
if (std::isalnum(c)) {
cleaned += std::tolower(c);
}
}
// Use two-pointer technique to check palindrome
int left = 0, right = cleaned.size() - 1;
while (left < right) {
if (cleaned[left] != cleaned[right]) {
return false;
}
++left;
--right;
}
return true;
}
};
// Example usage
int main() {
Solution solution;
std::string test1 = "A man, a plan, a canal: Panama";
std::string test2 = "race a car";
std::cout << std::boolalpha;
std::cout << "Test 1: " << solution.isPalindrome(test1) << std::endl;
std::cout << "Test 2: " << solution.isPalindrome(test2) << std::endl;
return 0;
}
Overall time complexity is O(n).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?