Skip to content

Commit c24e6be

Browse files
committed
add methods to 139
1 parent 4e5cb57 commit c24e6be

File tree

2 files changed

+26
-7
lines changed

2 files changed

+26
-7
lines changed

src/problems/139.word-break.jl

+14-1
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@
5050
using LeetCode
5151

5252
## BFS
53-
function word_break(s::String, word_dict::Vector{String})::Bool
53+
function word_break_bfs(s::String, word_dict::Vector{String})::Bool
5454
n, word_dict = length(s), sort!(word_dict; by=x -> length(x))
5555
valids, valid_pos = fill(false, n), [0]
5656
while !isempty(valid_pos)
@@ -66,4 +66,17 @@ function word_break(s::String, word_dict::Vector{String})::Bool
6666
end
6767
return false
6868
end
69+
70+
## Dynamic Programming
71+
function word_break(s::String, word_dict::Vector{String})::Bool
72+
lens = sort!(unique!(length.(word_dict)))
73+
dp = append!([true], fill(false, length(s)))
74+
for i in eachindex(dp)
75+
for len in lens
76+
i > len || break
77+
dp[i - len] && s[(i - len):(i - 1)] word_dict && (dp[i] = true)
78+
end
79+
end
80+
return last(dp)
81+
end
6982
## @lc code=end

test/problems/139.word-break.jl

+12-6
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,14 @@
11
@testset "139.word-break.jl" begin
2-
@test word_break("leetcode", ["leet", "code"]) == true
3-
@test word_break("catsandog", ["cats", "dog", "sand", "and", "cat"]) == false
4-
@test word_break("applepenapple", ["apple", "pen"]) == true
5-
@test word_break("a", ["b"]) == false
6-
@test word_break("a"^150 * "b", ["a"^i for i in 1:10]) == false
7-
@test word_break("bb", ["a", "b", "bbb", "bbbb"]) == true
2+
tcase1 = ("leetcode", ["leet", "code"])
3+
tcase2 = ("applepenapple", ["apple", "pen"])
4+
tcase3 = ("bb", ["a", "b", "bbb", "bbbb"])
5+
fcase1 = ("catsandog", ["cats", "dog", "sand", "and", "cat"])
6+
fcase2 = ("a", ["b"])
7+
fcase3 = ("a"^150 * "b", ["a"^i for i in 1:10])
8+
@test word_break(tcase1...) && word_break_bfs(tcase1...)
9+
@test word_break(tcase2...) && word_break_bfs(tcase2...)
10+
@test word_break(tcase3...) && word_break_bfs(tcase3...)
11+
@test !word_break(fcase1...) && !word_break_bfs(fcase1...)
12+
@test !word_break(fcase2...) && !word_break_bfs(fcase2...)
13+
@test !word_break(fcase3...) && !word_break_bfs(fcase3...)
814
end

0 commit comments

Comments
 (0)