A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.
Output: false
Explanation: "raceacar" is not a palindrome.
Output: true
Explanation: s is an empty string "" after removing non-alphanumeric characters. Since an empty string reads the same forward and backward, it is a palindrome.
Constraints:
- 1 <= s.length <= 2 * 105
-
s consists only of printable ASCII characters.
Contents
Solution 1 - Using two pointers approach
In this approach, we will use two pointers
Implementation steps:
-
We will first initialize two variables
start = 0 , andend = s.length() -1 , both points to left and right ends of the strings . -
While
start andend do not intersect each other, read the characters and check the followng:-
If left side character is not alpha-numeric : Increment
start pointer and continue. -
If right side character is not alpha-numeric : Decrement
end pointer and continue. -
Once above conditions are checked, then check whether left and right side characters are same or not (ignoring the case). If they are not same, then
return
false , otherwise incrementstart and decrementend to continue to next characters.
-
If left side character is not alpha-numeric : Increment
Complexity Analysis:
Time complexity: Above code runs in O(n) time where
Space complexity: O(1).
Above implementations source code can be found at