-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathword_break.rs
75 lines (65 loc) · 2.26 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
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
use std::collections::HashMap;
/// Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be
/// segmented into a space-separated sequence of one or more dictionary words.
///
/// Note that the same word in the dictionary may be reused multiple times in the segmentation.
struct Solution;
impl Solution {
fn worker(results: &mut HashMap<usize, bool>, word_dict: &Vec<String>, s: &str, index: usize) -> bool {
if results.contains_key(&index) {
results[&index]
} else {
let mut result = false;
let n = s.len();
let wd = word_dict.len();
for i in 0..wd {
let word = word_dict[i].as_str();
let word_len = word.len();
let end = index + word_len;
if end <= n {
if &s[index..end] == word {
if end == n {
result = true;
} else {
result = Self::worker(results, word_dict, s, end);
}
if result {
break;
}
}
}
}
results.insert(index, result);
result
}
}
pub fn word_break(s: String, word_dict: Vec<String>) -> bool {
let mut results = HashMap::new();
Self::worker(&mut results, &word_dict, &s, 0)
}
}
#[cfg(test)]
mod tests {
use super::Solution;
#[test]
fn example_1() {
let s = "leetcode".to_string();
let word_dict = vec!["leet".to_string(), "code".to_string()];
let result = Solution::word_break(s, word_dict);
assert!(result);
}
#[test]
fn example_2() {
let s = "applepenapple".to_string();
let word_dict = vec!["apple".to_string(), "pen".to_string()];
let result = Solution::word_break(s, word_dict);
assert!(result);
}
#[test]
fn example_3() {
let s = "catsandog".to_string();
let word_dict = vec!["cats".to_string(), "dog".to_string(), "sand".to_string(), "and".to_string(), "cat".to_string()];
let result = Solution::word_break(s, word_dict);
assert!(!result);
}
}