[LeetCode] Before and After Puzzle

1181. Before and After Puzzle

Given a list of phrases, generate a list of Before and After puzzles.

A phrase is a string that consists of lowercase English letters and spaces only. No space appears in the start or the end of a phrase. There are no consecutive spaces in a phrase.

Before and After puzzles are phrases that are formed by merging two phrases where the last word of the first phrase is the same as the first word of the second phrase.

Return the Before and After puzzles that can be formed by every two phrases phrases[i] and phrases[j] where i != j. Note that the order of matching two phrases matters, we want to consider both orders.

You should return a list of distinct strings sorted lexicographically.

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
class Solution {
pair<string, string> parse(string& s) {
string f = "", l = "";
for(int i = 0; i < s.length() and s[i] != ' '; i++) f.push_back(s[i]);
for(int i = s.length() - 1; i >= 0 and s[i] != ' '; i--) l.push_back(s[i]);
reverse(begin(l),end(l));
return {f,l};
}
public:
vector<string> beforeAndAfterPuzzles(vector<string>& phrases) {
unordered_map<string, vector<int>> first, last;
for(int i = 0; i < phrases.size(); i++) {
auto [f,l] = parse(phrases[i]);
first[f].push_back(i);
last[l].push_back(i);
}
unordered_set<string> us;

for(auto [k, vec] : last) {
for(auto& l : vec) {
for(auto& f : first[k]) {
if(l == f) continue;
string now = phrases[l] + phrases[f].substr(k.length());
us.insert(now);
}
}
}
vector<string> res(begin(us),end(us));
sort(begin(res),end(res));
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/25/PS/LeetCode/before-and-after-puzzle/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.