Last active
October 13, 2016 16:06
-
-
Save caelifer/4c6d0cbd67b6c0f0c058a12d10e24ff9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Playground link - https://play.golang.org/p/eHY8-zbUAa (does not work in playground).
Output: