Skip to content

Commit f9130a1

Browse files
authored
Create before-and-after-puzzle.cpp
1 parent 26da8ab commit f9130a1

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

C++/before-and-after-puzzle.cpp

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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+
};

0 commit comments

Comments
 (0)