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.
Input: phrases =["mission statement","a quick bite to eat","a chip off the old block","chocolate bar","mission impossible","a man on a mission","block party","eat my words","bar of soap"]Output: ["a chip off the old block party","a man on a mission impossible","a man on a mission statement","a quick bite to eat my words","chocolate bar of soap"]
To form a before and after puzzle, we need to efficiently find all pairs of phrases where the last word of one matches the first word of another. Using hash maps to group phrases by their first and last words allows us to quickly generate all valid combinations.
classSolution {
funbeforeAndAfterPuzzles(phrases: Array<String>): List<String> {
val first = mutableMapOf<String, MutableList<Int>>()
val n = phrases.size
for (i in0 until n) {
val ws = phrases[i].split(" ")
val fw = ws[0]
first.getOrPut(fw) { mutableListOf() }.add(i)
}
val ans = mutableSetOf<String>()
for (i in0 until n) {
val ws = phrases[i].split(" ")
val lw = ws.last()
for (j in first[lw] ?: emptyList()) {
if (i == j) continueval merged = phrases[i] + phrases[j].substring(lw.length)
ans.add(merged)
}
}
return ans.sorted()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution:
defbeforeAndAfterPuzzles(self, phrases: list[str]) -> list[str]:
from collections import defaultdict
first = defaultdict(list)
n = len(phrases)
for i, ph in enumerate(phrases):
ws = ph.split()
first[ws[0]].append(i)
ans = set()
for i, ph in enumerate(phrases):
ws = ph.split()
lw = ws[-1]
for j in first[lw]:
if i == j:
continue merged = ph + phrases[j][len(lw):]
ans.add(merged)
return sorted(ans)