Drill

ProblemsGo › patterns

Mirror text, ignoring the clutter

easypatternsTwo pointersStringsGo

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

isCleanPalindrome(text: string) → bool

Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

func isCleanPalindrome(text string) bool {
	
}

Worked examples

CallResult
isCleanPalindrome("race a car")false
isCleanPalindrome("A man, a plan, a canal: Panama")true
isCleanPalindrome("racecar")true
isCleanPalindrome(" ")true

Hint

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

Reference solution in Go
func isCleanPalindrome(text string) bool {
	alnum := func(c byte) bool {
	    return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
	}
	i, j := 0, len(text)-1
	for i < j {
	    a, b := text[i], text[j]
	    if !alnum(a) {
	        i++
	        continue
	    }
	    if !alnum(b) {
	        j--
	        continue
	    }
	    if a >= 'A' && a <= 'Z' {
	        a += 32
	    }
	    if b >= 'A' && b <= 'Z' {
	        b += 32
	    }
	    if a != b {
	        return false
	    }
	    i++
	    j--
	}
	return true
}

The same problem in another language

More patterns problems in Go