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
|
use std::collections::{HashMap, BTreeSet};
impl Solution {
pub fn generate_sentences(synonyms: Vec<Vec<String>>, text: String) -> Vec<String> {
let mut parent = HashMap::new();
fn find(x: &str, parent: &mut HashMap<String, String>) -> String {
if !parent.contains_key(x) { parent.insert(x.to_string(), x.to_string()); }
if parent[x] != x { let p = parent[x].clone(); parent.insert(x.to_string(), find(&p, parent)); }
parent[x].clone()
}
for p in &synonyms {
let a = find(&p[0], &mut parent);
let b = find(&p[1], &mut parent);
parent.insert(a, b);
}
let mut groups: HashMap<String, BTreeSet<String>> = HashMap::new();
for p in &synonyms {
let g = find(&p[0], &mut parent);
groups.entry(g.clone()).or_default().insert(p[0].clone());
groups.entry(g.clone()).or_default().insert(p[1].clone());
}
let words: Vec<&str> = text.split_whitespace().collect();
let mut options: Vec<Vec<String>> = vec![];
for word in &words {
let g = find(word, &mut parent);
if let Some(set) = groups.get(&g) {
options.push(set.iter().cloned().collect());
} else {
options.push(vec![word.to_string()]);
}
}
let mut res = vec![];
fn dfs(i: usize, options: &Vec<Vec<String>>, path: Vec<String>, res: &mut Vec<String>) {
if i == options.len() {
res.push(path.join(" "));
return;
}
for w in &options[i] {
let mut new_path = path.clone();
new_path.push(w.clone());
dfs(i+1, options, new_path, res);
}
}
dfs(0, &options, vec![], &mut res);
res.sort();
res
}
}
|