1
+ class Solution {
2
+ public:
3
+ unordered_set<string> visited;
4
+ unordered_map<string,vector<string>> adjList;
5
+ vector<string> dfs (string &s)
6
+ {
7
+ visited.insert (s);
8
+ vector<string> result,temp;
9
+ result.push_back (s);
10
+ for (string &next:adjList[s])
11
+ {
12
+ if (!visited.count (next))
13
+ temp=dfs (next);
14
+ result.insert (result.end (),temp.begin (),temp.end ());
15
+ }
16
+ return result;
17
+ }
18
+ vector<string> result;
19
+ string temp;
20
+ void create (string &s,int i)
21
+ {
22
+ if (i>=s.length ())
23
+ {
24
+ temp.pop_back ();
25
+ result.push_back (temp);
26
+ temp+=' ' ;
27
+ return ;
28
+ }
29
+ string word=s.substr (i,s.find (' ' ,i)-i);
30
+ int tmpbegin=temp.length ();
31
+ vector<string> tempList;
32
+ if (adjList.count (word))
33
+ {
34
+ visited.clear ();
35
+ tempList=dfs (word);
36
+ sort (tempList.begin (),tempList.end ());
37
+ for (string &next:tempList)
38
+ {
39
+ temp+=next+' ' ;
40
+ create (s,i+word.length ()+1 );
41
+ temp.erase (tmpbegin,temp.length ()-tmpbegin);
42
+ }
43
+ }
44
+ else
45
+ temp+=word+' ' ,create (s,i+word.length ()+1 ),temp.erase (tmpbegin,temp.length ()-tmpbegin);
46
+ }
47
+ vector<string> generateSentences (vector<vector<string>>& synonyms, string text)
48
+ {
49
+ for (vector<string> &v:synonyms)
50
+ adjList[v.front ()].push_back (v.back ()),adjList[v.back ()].push_back (v.front ());
51
+ create (text,0 );
52
+ return result;
53
+ }
54
+ };
0 commit comments