Drill

ProblemsPython › patterns

Mirror text, ignoring the clutter

easypatternsTwo pointersStringsPython

An audit tool checks whether a phrase reads the same forwards and backwards once the formatting — spaces, punctuation, digits — is stripped away.

is_clean_palindrome(text: string) → bool

Solve it in the editor →

Where you start

def is_clean_palindrome(text: str) -> bool:
    

Worked examples

CallResult
is_clean_palindrome("race a car")False
is_clean_palindrome("A man, a plan, a canal: Panama")True
is_clean_palindrome("racecar")True
is_clean_palindrome(" ")True

Hint

Walk from both ends at once, skipping anything that is not a letter or digit, and compare the survivors.

Reference solution in Python
def is_clean_palindrome(text: str) -> bool:
    i, j = 0, len(text) - 1
    while i < j:
        a, b = text[i], text[j]
        if not a.isalnum():
            i += 1
            continue
        if not b.isalnum():
            j -= 1
            continue
        if a.lower() != b.lower():
            return False
        i += 1
        j -= 1
    return True

The same problem in another language

More patterns problems in Python