Valid Palindrome
Easy strings · two-pointers
Description
Constraints
0 <= length <= 100000
Examples
Input: s = "A man, a plan, a canal: Panama"
Output: true
Input: s = "race a car"
Output: false
Hints (1)
- Keep two pointers moving inward and skip non-alphanumeric characters.
Solutions
Two pointers over normalised runes. (requires "strings","unicode") · Time O(n) · Space O(n)
func isPalindrome(s string) bool {
var b []rune
for _, r := range strings.ToLower(s) {
if unicode.IsLetter(r) || unicode.IsDigit(r) {
b = append(b, r)
}
}
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
if b[i] != b[j] {
return false
}
}
return true
}
Normalise, then compare with the reverse. · Time O(n) · Space O(n)
function isPalindrome(s) {
const c = s.toLowerCase().replace(/[^a-z0-9]/g, '');
return c === [...c].reverse().join('');
}
Normalise, then compare with the reverse. · Time O(n) · Space O(n)
function isPalindrome($s) {
$s = strtolower(preg_replace('/[^a-z0-9]/i', '', $s));
return $s === strrev($s);
}
Normalise, then compare with the reverse. · Time O(n) · Space O(n)
import re
def isPalindrome(s):
c = re.sub(r"[^a-z0-9]", "", s.lower())
return c == c[::-1]
Normalise, then compare with the reverse. · Time O(n) · Space O(n)
function isPalindrome(s: string): boolean {
const c = s.toLowerCase().replace(/[^a-z0-9]/g, '');
return c === [...c].reverse().join('');
}
Create a free account to submit solutions, track progress and save problems.
Create account