Skip to content

Commit c59b2c8

Browse files
author
openset
committed
Add: Word Break
1 parent 0f5b36c commit c59b2c8

File tree

3 files changed

+53
-0
lines changed

3 files changed

+53
-0
lines changed

internal/post/post.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,7 @@ var inPosts = map[int]bool{
138138
20: true,
139139
58: true,
140140
101: true,
141+
139: true,
141142
168: true,
142143
171: true,
143144
172: true,

problems/word-break/word_break.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,19 @@
11
package word_break
2+
3+
func wordBreak(s string, wordDict []string) bool {
4+
wm, l := make(map[string]bool), len(s)
5+
for _, w := range wordDict {
6+
wm[w] = true
7+
}
8+
dp := make([]bool, l+1)
9+
dp[0] = true
10+
for i := 1; i <= l; i++ {
11+
for j := 0; j < i; j++ {
12+
if dp[j] && wm[s[j:i]] {
13+
dp[i] = true
14+
break
15+
}
16+
}
17+
}
18+
return dp[l]
19+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,35 @@
11
package word_break
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
input string
7+
wordDict []string
8+
expected bool
9+
}
10+
11+
func TestWordBreak(t *testing.T) {
12+
tests := [...]caseType{
13+
{
14+
input: "leetcode",
15+
wordDict: []string{"leet", "code"},
16+
expected: true,
17+
},
18+
{
19+
input: "applepenapple",
20+
wordDict: []string{"apple", "pen"},
21+
expected: true,
22+
},
23+
{
24+
input: "catsandog",
25+
wordDict: []string{"cats", "dog", "sand", "and", "cat"},
26+
expected: false,
27+
},
28+
}
29+
for _, tc := range tests {
30+
output := wordBreak(tc.input, tc.wordDict)
31+
if output != tc.expected {
32+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
33+
}
34+
}
35+
}

0 commit comments

Comments
 (0)