Complete the code to check if the input string is empty.
if s.[1]() { return true; }
The is_empty() method checks if the string has zero length, which means it's empty.
Complete the code to iterate over the dictionary words.
for word in word_dict.[1]() { /* check prefix */ }
The iter() method returns an iterator over references to the elements, suitable for checking each word.
Fix the error in the prefix check condition.
if s.starts_with([1]) { /* proceed */ }
The starts_with method expects a string slice (&str), so we convert the String to &str using as_str().
Fill both blanks to slice the string and recursively check the rest.
let suffix = &s[[1]..]; if word_break(suffix, word_dict) == [2] { return true; }
We slice the string from the length of the matched word to the end, then recursively check if the suffix can be segmented. If it returns true, we return true.
Fill all three blanks to complete the word break function with memoization.
fn word_break_memo(s: &str, word_dict: &Vec<String>, memo: &mut std::collections::HashMap<String, bool>) -> bool {
if s.is_empty() { return true; }
if let Some(&result) = memo.get(&s.to_string()) {
return [1];
}
for word in word_dict.iter() {
if s.starts_with(word.as_str()) {
let suffix = &s[[2]..];
if word_break_memo(suffix, word_dict, memo) == [3] {
memo.insert(s.to_string(), true);
return true;
}
}
}
memo.insert(s.to_string(), false);
false
}We return the cached result if present. The suffix is sliced from the length of the matched word. If the recursive call returns true, we cache and return true.
