A palindrome reads the same forwards and backwards. Check whether the string s is one, looking only at its letters and digits.
- Letters are
a–zandA–Z. Digits are0–9. Skip everything else, such as spaces, punctuation and symbols. - Upper and lower case count as equal, so
"A"matches"a". - Return
trueif the kept characters read the same both ways, andfalseif they don't. - An empty string counts as a palindrome. So does a string with no letters or digits at all.
scan be up to 100,000 characters long.- Try to use O(1) extra memory, which means a fixed amount that doesn't grow with
s. So don't build a cleaned copy of the string.
Input: s = "Taco cat"
Output: trueIf you ignore the space and the case, it reads "tacocat" both ways.
Input: s = "Was it a car or a cat I saw?"
Output: true
Input: s = "race a car"
Output: falseKeep only the letters and you get "raceacar". Backwards it is "racaecar", which is different.