Skip to content

Instantly share code, notes, and snippets.

@caelifer
Last active October 13, 2016 16:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caelifer/4c6d0cbd67b6c0f0c058a12d10e24ff9 to your computer and use it in GitHub Desktop.
Save caelifer/4c6d0cbd67b6c0f0c058a12d10e24ff9 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"unicode"
"golang.org/x/text/unicode/norm"
)
func main() {
tests := []struct {
t string
res bool
}{
{"", true},
{"a", true},
{"A ny你y, na", true},
{"any你ad", false},
{"aéa", true},
}
for _, tc := range tests {
if res := isPalindrome(tc.t); res != tc.res {
fmt.Printf("[FAIL] for %q got %t; expected %t\n", tc.t, res, tc.res)
} else {
pass := "is"
if res == false {
pass = "is not"
}
fmt.Printf("[PASS] %q %s a palindrome\n", tc.t, pass)
}
}
}
func isPalindrome(s string) bool {
t := clean(s)
l := len(t)
for i := 0; i < l/2; i++ {
if t[i] != t[l-i-1] {
return false
}
}
return true
}
// remove non-letters and convert to lower case
func clean(s string) []rune {
t := []rune(string(norm.NFC.Bytes([]byte(s)))) // Normalize and convert to []rune
c := 0 // insert index
for _, r := range t {
if unicode.IsLetter(r) {
t[c] = unicode.ToLower(r)
c++
}
}
return t[:c]
}
@caelifer
Copy link
Author

caelifer commented Oct 13, 2016

Playground link - https://play.golang.org/p/eHY8-zbUAa (does not work in playground).
Output:

[PASS] "" is a palindrome
[PASS] "a" is a palindrome
[PASS] "A ny你y, na" is a palindrome
[PASS] "any你ad" is not a palindrome
[PASS] "aéa" is a palindrome

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment