-
Notifications
You must be signed in to change notification settings - Fork 481
/
Copy path1258.cpp
52 lines (49 loc) · 1.32 KB
/
1258.cpp
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
class Solution
{
public:
vector<string> generateSentences(vector<vector<string>>& synonyms, string text)
{
for (auto& it : synonyms)
{
string x = find(it[0]), y = find(it[1]);
if (x != y) parent[x] = y;
}
for (auto& k : parent) data[find(k.first)].push_back(k.first);
stringstream ss(text);
string w;
vector<string> res = {""};
while (ss >> w)
{
auto fw = find(w);
if (data.count(fw))
{
vector<string> tmp;
for (auto& s : res)
{
for (auto& v : data[fw])
{
tmp.push_back(s + " " + v);
}
}
res = tmp;
}
else
{
for (auto& s : res)
s += " " + w;
}
}
for (auto& it : res) it = it.substr(1);
sort(res.begin(), res.end());
return res;
}
private:
unordered_map<string, string> parent;
unordered_map<string, vector<string>> data;
string find(const string& x)
{
if (!parent.count(x)) parent[x] = x;
if (x != parent[x]) parent[x] = find(parent[x]);
return parent[x];
}
};