DevPath

← All problems

Valid Palindrome

Easy strings · two-pointers

Description

Return true if the string reads the same forwards and backwards, ignoring case and any character that is not a letter or digit.

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
}

Create a free account to submit solutions, track progress and save problems.

Create account