📝 Problem Details
- Title:
125. Valid Palindrome
- Link: https://leetcode.com/problems/valid-palindrome/
- Difficulty: Easy
- Tags/Categories: Two-Pointers Strings
input string
s
returntrue
ifs
is a palindrome,false
otherwise
💡 Explanation of Solution
- two pointers approach
- i set to the start of the string
- j set to the end of the string
- move them closer each iteration
- have two nested while loops to prevent non-alphanumeric characters from breaking the two pointers comparison
⌛ Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1)
💻 Implementation of Solution
class Solution {
public:
bool isPalindrome(string s) {
int i = 0;
int j = s.size()-1;
while(i < j) {
while(!isalnum(s[i]) && i < j) i++;
while(!isalnum(s[j]) && i < j) j--;
if(tolower(s[i]) != tolower(s[j]))
return false;
i++;
j--;
}
return true;
}
};