Stringsstrings-palindrome
LessonΒ·difficulty 2/5Β·~12 min
Strings: valid palindrome
Strings: valid palindrome
A palindrome reads the same forwards and backwards: "level", "noon".
Strings in Python support handy tools:
python
s = "Hello"
s.lower() # "hello"
s[::-1] # "olleH" β slicing with step -1 reverses
"a1".isalnum() # checks letters/digits, char by char
This is LeetCode #125. We only care about letters and digits, and we
ignore case. So "A man, a plan, a canal: Panama" is a valid palindrome.
Your task
Write is_palindrome(s) that returns True if s is a palindrome once you:
- drop every character that is not a letter or digit, and
- compare case-insensitively.
python
is_palindrome("A man, a plan, a canal: Panama") # True
is_palindrome("race a car") # False
is_palindrome("") # True (nothing to contradict it)
Hint: build a cleaned list of c.lower() for each c where c.isalnum(),
then compare it to its reverse.
Tests
- classic with punctuation
- not a palindrome
- empty string
- mixed case digits
- single non-alnum (hidden)
Stuck? Ask for a spark
warming up
Loading editorβ¦
$ Console output will appear here.