-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhello.go
More file actions
65 lines (57 loc) · 1.27 KB
/
Copy pathhello.go
File metadata and controls
65 lines (57 loc) · 1.27 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
package main
import (
"fmt"
"hello-go/grammar/note"
"strings"
)
func main() {
wordBreak("catsanddog", []string{"cat", "cats", "and", "sand", "dog"})
fmt.Println("hello world!") // in current function
sayHello() // in current file
//speakHello() // in current package
note.SayHello() // in other package
fmt.Println()
}
func sayHello() {
fmt.Println("hello!")
}
func wordBreak(s string, wordDict []string) []string {
dictMap := make(map[string]bool)
maxLen := 0
for _, w := range wordDict {
dictMap[w] = true
if len(w) > maxLen {
maxLen = len(w)
}
}
result := make([][]string, 0)
var helper func(reminder string, words []string)
helper = func(reminder string, words []string) {
if len(reminder) == 0 {
result = append(result, words)
return
}
for i := 1; i <= min(maxLen, len(reminder)); i++ {
w := reminder[:i]
if dictMap[w] {
newWords := make([]string, len(words))
copy(newWords, words)
newWords = append(newWords, w)
helper(reminder[i:], newWords)
}
}
}
helper(s, []string{})
ans := make([]string, len(result))
for i := 0; i < len(result); i++ {
wordList := result[i]
ans[i] = strings.Join(wordList, " ")
}
return ans
}
func min(a int, b int) int {
if a < b {
return a
}
return b
}