-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
91 lines (78 loc) · 1.31 KB
/
main.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"bufio"
"io"
"strings"
)
func fs1(input io.Reader) (int, error) {
scanner := bufio.NewScanner(input)
sum := 0
for scanner.Scan() {
if isValid(scanner.Text()) {
sum++
}
}
return sum, nil
}
func isValid(s string) bool {
words := strings.Split(s, " ")
set := make(map[string]struct{})
for _, word := range words {
if _, exists := set[word]; exists {
return false
}
set[word] = struct{}{}
}
return true
}
func fs2(input io.Reader) (int, error) {
scanner := bufio.NewScanner(input)
sum := 0
for scanner.Scan() {
if isValid2(scanner.Text()) {
sum++
}
}
return sum, nil
}
func isValid2(s string) bool {
words := strings.Split(s, " ")
for i := 0; i < len(words); i++ {
a := words[i]
for j := 0; j < i; j++ {
b := words[j]
if isAnagram(a, b) {
return false
}
}
}
return true
}
func isAnagram(a, b string) bool {
if len(a) != len(b) {
return false
}
lettersA := make(map[rune]int)
for i := 0; i < len(a); i++ {
r := rune(a[i])
lettersA[r]++
}
lettersB := make(map[rune]int)
for i := 0; i < len(b); i++ {
r := rune(b[i])
lettersB[r]++
}
if len(lettersA) != len(lettersB) {
return false
}
for k, v := range lettersA {
v2, exists := lettersB[k]
if !exists {
return false
}
if v != v2 {
return false
}
}
return true
}