-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path49.group-anagrams.go
More file actions
73 lines (66 loc) · 1.12 KB
/
49.group-anagrams.go
File metadata and controls
73 lines (66 loc) · 1.12 KB
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
/*
* @lc app=leetcode id=49 lang=golang
*
* [49] Group Anagrams
*/
// @lc code=start
import (
"sort"
"strings"
)
func groupAnagrams(strs []string) [][]string {
res := [][]string{}
m := make(map[string][]int)
// O(n*mlogm)
for i, value := range strs {
sortedStr := SortString(value)
_, exist := m[sortedStr]
if exist == true {
m[sortedStr] = append(m[sortedStr], i)
} else {
m[sortedStr] = []int{i}
}
}
// O(n*n)
for _, value := range m {
temp := []string{}
for _, index := range value {
temp = append(temp, strs[index])
}
res = append(res, temp)
}
return res
}
// O(mlogm)
func SortString(w string) string {
s := strings.Split(w, "")
sort.Strings(s)
return strings.Join(s, "")
}
func isAnagram(s string, t string) bool {
if len(s) != len(t) {
return false
}
m := make(map[byte]int)
for i := 0; i < len(s); i++ {
_, exist := m[s[i]]
if exist == true {
m[s[i]]++
} else {
m[s[i]] = 1
}
_, exist = m[t[i]]@
if exist == true {
m[t[i]]--
} else {
m[t[i]] = -1
}
}
for value := range m {
if m[value] != 0 {
return false
}
}
return true
}
// @lc code=end