-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution819.go
51 lines (45 loc) · 1.02 KB
/
solution819.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
package solution819
import (
"strings"
"unicode"
)
// ============================================================================
// 819. Most Common Word
// URL: https://leetcode.com/problems/most-common-word/
// ============================================================================
/*
$ go test -bench=. -benchmem
goos: linux
goarch: amd64
cpu: 13th Gen Intel(R) Core(TM) i7-13700K
Benchmark_mostCommonWord-24 1000000 1084 ns/op 4336 B/op 5 allocs/op
PASS
*/
func mostCommonWord(paragraph string, banned []string) string {
output := ""
maxval := 0
words := strings.FieldsFunc(paragraph, func(r rune) bool {
return unicode.IsSpace(r) || !unicode.IsLetter(r)
})
m := make(map[string]int, len(paragraph))
outer:
for _, word := range words {
w := strings.ToLower(word)
for _, bword := range banned {
if bword == w {
continue outer
}
}
_, ok := m[w]
if ok {
m[w]++
} else {
m[w] = 1
}
if maxval < m[w] {
maxval = m[w]
output = w
}
}
return output
}