Skip to content

Commit 7934fba

Browse files
authored
Merge pull request algorithm004-01#380 from weapon008/master
451-Week 02
2 parents 7e6fb19 + 2bc5ada commit 7934fba

File tree

3 files changed

+119
-0
lines changed

3 files changed

+119
-0
lines changed

Week 02/id_451/LeetCode_144_451.go

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* type TreeNode struct {
4+
* Val int
5+
* Left *TreeNode
6+
* Right *TreeNode
7+
* }
8+
*/
9+
type Stack struct {
10+
list *list.List
11+
}
12+
13+
func NewStack() *Stack {
14+
list := list.New()
15+
return &Stack{list}
16+
}
17+
18+
func (stack *Stack) Push(value interface{}) {
19+
stack.list.PushBack(value)
20+
}
21+
22+
func (stack *Stack) Pop() interface{} {
23+
e := stack.list.Back()
24+
if e != nil {
25+
stack.list.Remove(e)
26+
return e.Value
27+
}
28+
return nil
29+
}
30+
func (stack *Stack) Len() int {
31+
return stack.list.Len()
32+
}
33+
func preorderTraversal(root *TreeNode) (res []int) {
34+
s := NewStack()
35+
t := root
36+
for t != nil || s.Len() > 0 {
37+
if t == nil {
38+
t = s.Pop().(*TreeNode)
39+
t = t.Right
40+
continue
41+
}
42+
res = append(res, t.Val)
43+
s.Push(t)
44+
t = t.Left
45+
}
46+
return
47+
}

Week 02/id_451/LeetCode_49_451.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
2+
type hash map[rune]int
3+
4+
func NewHash() hash {
5+
hmap := make(hash)
6+
return hmap
7+
}
8+
9+
func (hm hash) hash(s string) (hs string) {
10+
for _, a := range s {
11+
hm[a] += 1
12+
}
13+
for i := 0; i < 26; i++ {
14+
a := rune(97 + i)
15+
hs += fmt.Sprintf(`%s:%d,`, a, hm[a])
16+
}
17+
return hs
18+
}
19+
20+
func groupAnagrams(strs []string) (lres [][]string) {
21+
res := make(map[string][]string)
22+
for _, s := range strs {
23+
hmap := NewHash()
24+
h := hmap.hash(s)
25+
res[h] = append(res[h], s)
26+
}
27+
28+
for _, s := range res {
29+
lres = append(lres, s)
30+
}
31+
return
32+
}

Week 02/id_451/LeetCode_94_451.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
type Stack struct {
2+
list *list.List
3+
}
4+
5+
func NewStack() *Stack {
6+
list := list.New()
7+
return &Stack{list}
8+
}
9+
10+
func (stack *Stack) Push(value interface{}) {
11+
stack.list.PushBack(value)
12+
}
13+
14+
func (stack *Stack) Pop() interface{} {
15+
e := stack.list.Back()
16+
if e != nil {
17+
stack.list.Remove(e)
18+
return e.Value
19+
}
20+
return nil
21+
}
22+
func (stack *Stack) Len() int {
23+
return stack.list.Len()
24+
}
25+
26+
func inorderTraversal(root *TreeNode) (res []int) {
27+
s := NewStack()
28+
t := root
29+
for t != nil || s.Len() > 0 {
30+
if t == nil {
31+
t = s.Pop().(*TreeNode)
32+
res = append(res, t.Val)
33+
t = t.Right
34+
continue
35+
}
36+
s.Push(t)
37+
t = t.Left
38+
}
39+
return
40+
}

0 commit comments

Comments
 (0)