-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathword_break.rs
48 lines (45 loc) · 1.08 KB
/
word_break.rs
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
#![allow(dead_code)]
pub fn word_break(s: String, word_dict: Vec<String>) -> bool {
let word_set: std::collections::HashSet<_> = word_dict.into_iter().collect();
let mut dp = vec![false; s.len() + 1];
dp[0] = true;
for i in 1..=s.len() {
for j in 0..i {
if dp[j] && word_set.contains(&s[j..i]) {
dp[i] = true;
break;
}
}
}
dp[s.len()]
}
#[test]
fn test_word_break() {
assert_eq!(
word_break(
"leetcode".to_string(),
vec!["leet".to_string(), "code".to_string()]
),
true
);
assert_eq!(
word_break(
"applepenapple".to_string(),
vec!["apple".to_string(), "pen".to_string()]
),
true
);
assert_eq!(
word_break(
"catsandog".to_string(),
vec![
"cats".to_string(),
"dog".to_string(),
"sand".to_string(),
"and".to_string(),
"cat".to_string()
]
),
false
);
}