Skip to content

Commit bdfbe9f

Browse files
Merge pull request algorithm001#712 from zhaowende/master
123号学员 第四周作业
2 parents 4945cc7 + dbe0567 commit bdfbe9f

4 files changed

Lines changed: 169 additions & 0 deletions

File tree

Week_04/id_123/LeetCode_455_123.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package id_123
2+
3+
import (
4+
"sort"
5+
)
6+
7+
func findContentChildren(g []int, s []int) int {
8+
count := 0
9+
10+
sort.Ints(g)
11+
sort.Ints(s)
12+
13+
for _, needSize := range g {
14+
for index, actualSize := range s {
15+
if needSize <= actualSize {
16+
count += 1
17+
s = s[index+1:]
18+
break
19+
}
20+
}
21+
}
22+
23+
return count
24+
}

Week_04/id_123/LeetCode_455_123_test.go

Lines changed: 63 additions & 0 deletions
Large diffs are not rendered by default.

Week_04/id_123/LeetCode_720_123.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package id_123
2+
3+
type TrieNode struct {
4+
data byte
5+
children [26]*TrieNode
6+
isEndingChar bool
7+
}
8+
9+
// 往 Trie 树中插入一个字符串
10+
func insert(root *TrieNode, text string) {
11+
p := root
12+
for i := 0; i < len(text); i++ {
13+
index := text[i] - 'a'
14+
if p.children[index] == nil {
15+
newNode := &TrieNode{data: text[i]}
16+
p.children[index] = newNode
17+
}
18+
p = p.children[index]
19+
}
20+
p.isEndingChar = true
21+
}
22+
23+
func longestWord(words []string) string {
24+
root := &TrieNode{}
25+
for _, word := range words {
26+
insert(root, word)
27+
}
28+
29+
finalResult := ""
30+
tempStr := ""
31+
findLongestWord(root, &tempStr, &finalResult)
32+
return finalResult
33+
}
34+
35+
func findLongestWord(root *TrieNode, resWord *string, finalResult *string) {
36+
for i := 0; i < 26; i++ {
37+
if root.children[i] != nil && root.children[i].isEndingChar {
38+
newStr := *resWord + string(root.children[i].data)
39+
if len(newStr) > len(*finalResult) {
40+
*finalResult = newStr
41+
}
42+
43+
findLongestWord(root.children[i], &newStr, finalResult)
44+
}
45+
}
46+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package id_123
2+
3+
import "testing"
4+
5+
func Test_longestWord(t *testing.T) {
6+
type args struct {
7+
words []string
8+
}
9+
tests := []struct {
10+
name string
11+
args args
12+
want string
13+
}{
14+
{
15+
name: "test1",
16+
args: args{
17+
words: []string{"w", "wo", "wor", "worl", "world"},
18+
},
19+
want: "world",
20+
},
21+
{
22+
name: "test2",
23+
args: args{
24+
words: []string{"b", "bo", "boy", "w", "wo", "wor", "worl", "world"},
25+
},
26+
want: "world",
27+
},
28+
}
29+
for _, tt := range tests {
30+
t.Run(tt.name, func(t *testing.T) {
31+
if got := longestWord(tt.args.words); got != tt.want {
32+
t.Errorf("longestWord() = %v, want %v", got, tt.want)
33+
}
34+
})
35+
}
36+
}

0 commit comments

Comments
 (0)