Skip to main content

DSA: Character Classification for Palindromes

DSA

Check whether a Swift character is a letter or number, and skip spaces and special characters during palindrome checks.

Palindrome problems commonly compare only letters and numbers. Treat every other character, including spaces, punctuation, and symbols, as ignorable.

func isAlphanumeric(_ character: Character) -> Bool {
    character.isLetter || character.isNumber
}

func shouldIgnoreForPalindrome(_ character: Character) -> Bool {
    !isAlphanumeric(character)
}

isAlphanumeric("A")               // true
isAlphanumeric("7")               // true
shouldIgnoreForPalindrome(" ")    // true
shouldIgnoreForPalindrome("!")    // true

Use the helpers while moving two pointers inward. Skip ignored characters before comparing the remaining characters, usually after normalizing their case.

Swift’s Character.isLetter and Character.isNumber properties are Unicode-aware, so this works beyond ASCII letters and digits.