I've solved this problem: https://leetcode.com/problems/word-break
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
Note:
The same word in the dictionary may be reused multiple times in the segmentation. You may assume the dictionary does not contain duplicate words. Example 1:
impl Solution {
fn dfs(i: usize, words: &HashSet<String>, cur_word: &str, cache: &mut HashMap<usize, bool>, n: usize, orig:&str) -> bool {
if i == n {
return true;
}
if cache.contains_key(&i) {
return *cache.get(&i).unwrap();
}
if words.contains(cur_word) {
cache.insert(i, true);
return true;
}
let mut res = String::from("");
for k in i..n {
let s = orig.chars().nth(k).unwrap();
res.push(s);
if words.contains(&res) && Self::dfs(k + 1, &words, orig.get(k+ 1..).unwrap_or_default(), cache, n, orig) {
cache.insert(i, true);
return true;
}
}
cache.insert(i, false);
return false;
}
pub fn word_break(s: String, word_dict: Vec<String>) -> bool {
let set = word_dict.into_iter().collect::<HashSet<String>>();
let mut cache = HashMap::new();
Self::dfs(0, &set, "", &mut cache, s.len(), &s)
}
}
Please ignore the useless Solution
struct -- that's part of the website's interface for solution.
I'm quite upset with how my dfs
function is structured -- I am passing far too many arguments into it.
In python, I would've simply created a recursive nested function, which would have captured outer variables; rust doesn't allow for recursive closures, as a closure is an unnamed struct. So I've had to resort to creating a argument-heavy function.
How do I make my code more idiomatic?