Palindrome
Description
Given a string s, return true if it is a palindrome (reads the same forward and backward), or false otherwise. Consider only alphanumeric characters and ignore case.
Example 1:
Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: After removing non-alphanumeric and lowercasing: "amanaplanacanalpanama" is a palindrome.
Example 2:
Input: s = "race a car"
Output: false
Explanation: After processing: "raceacar" is not a palindrome.
Example 3:
Input: s = " "
Output: true
Explanation: After removing non-alphanumeric: "" (empty string) is a palindrome.
Constraints
1 <= s.length <= 2 * 10^5s consists of printable ASCII characters
Signature
...Complexity
- Time:
O(n) - Space:
O(1)
Hints
- Pattern
- Use two pointers: one at the start, one at the end
- Approach
- Move pointers inward, skipping non-alphanumeric chars. Compare lowercase versions.
- Complexity
- You only need to traverse the string once - O(n) time, O(1) space
Solutions
go 0 (T.length t - 1)
where
go l r
| l >= r = True
| T.index t l /= T.index t r = False
| otherwise = go (l + 1) (r - 1)
bool
using namespace std;
bool
return True
= 0
= - 1
return False
+= 1
-= 1
return True