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.
Example 1:
Input: phrases = ["writing code","code rocks"] Output: ["writing code rocks"]
Example 2:
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"]
Example 3:
Input: phrases = ["a","b","a"] Output: ["a"]
Constraints:
1 <= phrases.length <= 100
1 <= phrases[i].length <= 100
class Solution:
def beforeAndAfterPuzzles(self, phrases: List[str]) -> List[str]:
same_first_word = defaultdict(set)
for i, phrase in enumerate(phrases):
same_first_word[phrase.split()[0]].add(i)
res = set()
for i, phrase in enumerate(phrases):
words = phrase.split()
last_word = words[-1]
if last_word in same_first_word:
for j in same_first_word[last_word]:
if i != j:
res.add(' '.join(words[:-1] + phrases[j].split()))
return sorted(list(res))
class Solution {
public List<String> beforeAndAfterPuzzles(String[] phrases) {
Map<String, Set<Integer>> sameFirstWord = new HashMap<>();
for (int i = 0; i < phrases.length; ++i) {
String phrase = phrases[i];
String word = phrase.split(" ")[0];
sameFirstWord.computeIfAbsent(word, k -> new HashSet<>()).add(i);
}
Set<String> res = new HashSet<>();
for (int i = 0; i < phrases.length; ++i) {
String phrase = phrases[i];
String[] words = phrase.split(" ");
String lastWord = words[words.length - 1];
if (sameFirstWord.containsKey(lastWord)) {
for (int j : sameFirstWord.get(lastWord)) {
if (i != j) {
List<String> t = new ArrayList<>();
for (int k = 0; k < words.length - 1; ++k) {
t.add(words[k]);
}
for (String word : phrases[j].split(" ")) {
t.add(word);
}
res.add(String.join(" ", t));
}
}
}
}
List<String> output = new ArrayList<>(res);
Collections.sort(output);
return output;
}
}