/
palindrome.go
50 lines (46 loc) · 1.09 KB
/
palindrome.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package main
import (
"fmt"
"os"
"path/filepath"
"unicode/utf8"
)
var IsPalindrome func(string) bool // Holds a reference to a function
func init() {
if len(os.Args) > 1 &&
(os.Args[1] == "-a" || os.Args[1] == "--ascii") {
os.Args = append(os.Args[:1], os.Args[2:]...) // Strip out arg.
IsPalindrome = func(s string) bool { // Simple ASCII-only version
if len(s) <= 1 {
return true
}
if s[0] != s[len(s)-1] {
return false
}
return IsPalindrome(s[1 : len(s)-1])
}
} else {
IsPalindrome = func(s string) bool { // UTF-8 version
if utf8.RuneCountInString(s) <= 1 {
return true
}
first, sizeOfFirst := utf8.DecodeRuneInString(s)
last, sizeOfLast := utf8.DecodeLastRuneInString(s)
if first != last {
return false
}
return IsPalindrome(s[sizeOfFirst : len(s)-sizeOfLast])
}
}
}
func main() {
if len(os.Args) == 1 {
fmt.Printf("usage: %s [-a|--ascii] word1 [word2 [... wordN]]\n",
filepath.Base(os.Args[0]))
os.Exit(1)
}
words := os.Args[1:]
for _, word := range words {
fmt.Printf("%5t %q\n", IsPalindrome(word), word)
}
}