-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path139.单词拆分.go
90 lines (76 loc) · 2.11 KB
/
139.单词拆分.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
* @lc app=leetcode.cn id=139 lang=golang
*
* [139] 单词拆分
*/
package main
import "fmt"
import "strings"
func main() {
var s string
var wordDict []string
s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab"
wordDict = []string{"a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"}
fmt.Printf("%s, %v, %t\n", s, wordDict, wordBreak(s, wordDict))
return
s = "catsandogcat"
wordDict = []string{"cats","dog","sand","and","cat","an"}
fmt.Printf("%s, %v, %t\n", s, wordDict, wordBreak(s, wordDict))
s = "ccbb"
wordDict = []string{"bc", "cb"}
fmt.Printf("%s, %v, %t\n", s, wordDict, wordBreak(s, wordDict))
s = "cars"
wordDict = []string{"car","ca","rs"}
fmt.Printf("%s, %v, %t\n", s, wordDict, wordBreak(s, wordDict))
s = "leetcode"
wordDict = []string{"leet", "code"}
fmt.Printf("%s, %v, %t\n", s, wordDict, wordBreak(s, wordDict))
s = "applepenapple"
wordDict = []string{"apple", "pen"}
fmt.Printf("%s, %v, %t\n", s, wordDict, wordBreak(s, wordDict))
s = "catsandog"
wordDict = []string{"cats", "dog", "sand", "and", "cat"}
fmt.Printf("%s, %v, %t\n", s, wordDict, wordBreak(s, wordDict))
}
// @lc code=start
func wordBreak2(s string, wordDict []string) bool {
var dfs func(string)
n := len(wordDict)
var isOk bool
isOk = false
dfs = func(left string) {
if isOk == true {
return
}
if len(left) == 0 {
isOk = true
}
for i := 0 ; i < n ; i ++ {
index := strings.Index(left, wordDict[i])
if index == 0 {
newLeft := left[len(wordDict[i]):]
dfs(newLeft)
}
}
}
dfs(s)
return isOk
}
// @lc code=end
func wordBreak(s string, wordDict []string) bool {
wordDictSet := make(map[string]bool)
for _, w := range wordDict {
wordDictSet[w] = true
}
dp := make([]bool, len(s) + 1)
dp[0] = true
for i := 1; i <= len(s); i++ {
for j := 0; j < i; j++ {
if dp[j] && wordDictSet[s[j:i]] {
dp[i] = true
break
}
}
}
return dp[len(s)]
}