|
@@ -0,0 +1,82 @@
|
|
|
+struct Solution;
|
|
|
+
|
|
|
+use std::collections::{HashMap, HashSet};
|
|
|
+
|
|
|
+impl Solution {
|
|
|
+ pub fn word_break(s: String, word_dict: Vec<String>) -> bool {
|
|
|
+ let mut min_length = usize::MAX;
|
|
|
+ let mut max_length = 0;
|
|
|
+ let mut word_dict_2 = HashSet::new();
|
|
|
+ for w in word_dict {
|
|
|
+ let l = w.len();
|
|
|
+ if l < min_length { min_length = l; }
|
|
|
+ if l > max_length { max_length = l; }
|
|
|
+ word_dict_2.insert(w);
|
|
|
+ }
|
|
|
+ let mut dp = HashMap::new();
|
|
|
+ Solution::helper(s.clone(), &word_dict_2, &mut dp, 0, s.len(), min_length, max_length)
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+ fn helper(s: String, word_dict: &HashSet<String>, dp: &mut HashMap<(usize, usize), bool>, i: usize, j: usize, min_length: usize, max_length: usize) -> bool {
|
|
|
+ if dp.contains_key(&(i, j)) {
|
|
|
+ return *dp.get(&(i, j)).unwrap();
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ if word_dict.contains(&s[i..j].to_string()) {
|
|
|
+ dp.insert((i, j), true);
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+
|
|
|
+ let mut res = false;
|
|
|
+ for k in i+1..j {
|
|
|
+ if j - k > max_length { continue; }
|
|
|
+ if j - k < min_length { continue; }
|
|
|
+
|
|
|
+ res = res || (Solution::helper(s.clone(), word_dict, dp, k, j, min_length, max_length) && Solution::helper(s.clone(), word_dict, dp, i, k, min_length, max_length));
|
|
|
+ if res {
|
|
|
+ break;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ dp.insert((i, j), res);
|
|
|
+
|
|
|
+ res
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+}
|
|
|
+
|
|
|
+#[cfg(test)]
|
|
|
+mod tests {
|
|
|
+ use super::*;
|
|
|
+
|
|
|
+ #[test]
|
|
|
+ fn test_word_break() {
|
|
|
+ let s = String::from("applepenapple");
|
|
|
+ let word_dict = vec!["apple","pen"];
|
|
|
+ let word_dict = word_dict.into_iter().map(|x| x.to_string()).collect::<Vec<String>>();
|
|
|
+ let res = Solution::word_break(s, word_dict);
|
|
|
+
|
|
|
+ assert_eq!(res, true);
|
|
|
+
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+ #[test]
|
|
|
+ fn test_word_break2() {
|
|
|
+ let s = String::from("aaaaaaa");
|
|
|
+ let word_dict = vec!["aaaa","aaa"];
|
|
|
+ let word_dict = word_dict.into_iter().map(|x| x.to_string()).collect::<Vec<String>>();
|
|
|
+ let res = Solution::word_break(s, word_dict);
|
|
|
+
|
|
|
+ assert_eq!(res, true);
|
|
|
+
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+}
|