File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time: O(l * rlogr) , l is the max length of phrases
2
+ // , r is the number of result, could be up to O(n^2)
3
+ // Space: O(l * (n + r)), n is the number of phrases
4
+
5
+ class Solution {
6
+ public:
7
+ vector<string> beforeAndAfterPuzzles (vector<string>& phrases) {
8
+ unordered_map<string, vector<size_t >> lookup;
9
+ for (int i = 0 ; i < phrases.size (); ++i) {
10
+ const auto & phrase = phrases[i];
11
+ const auto & right = phrase.rfind (' ' );
12
+ const auto & word = (right == string::npos) ? phrase : phrase.substr (right + 1 );
13
+ lookup[word].emplace_back (i);
14
+ }
15
+ unordered_set<string> result_set;
16
+ for (int i = 0 ; i < phrases.size (); ++i) {
17
+ const auto & phrase = phrases[i];
18
+ const auto & left = phrase.find (' ' );
19
+ const auto & word = (left == string::npos) ? phrase : phrase.substr (0 , left);
20
+ if (!lookup.count (word)) {
21
+ continue ;
22
+ }
23
+ for (const auto & j : lookup[word]) {
24
+ if (j == i) {
25
+ continue ;
26
+ }
27
+ result_set.emplace (phrases[j] + phrase.substr (word.length ()));
28
+ }
29
+ }
30
+ vector<string> result (result_set.cbegin (), result_set.cend ());
31
+ sort (result.begin (), result.end ());
32
+ return result;
33
+ }
34
+ };
You can’t perform that action at this time.
0 commit comments