Skip to content

Commit fe908fc

Browse files
committed
Add solution #1181
1 parent c1d104e commit fe908fc

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1103,6 +1103,7 @@
11031103
1177|[Can Make Palindrome from Substring](./solutions/1177-can-make-palindrome-from-substring.js)|Medium|
11041104
1178|[Number of Valid Words for Each Puzzle](./solutions/1178-number-of-valid-words-for-each-puzzle.js)|Hard|
11051105
1180|[Count Substrings with Only One Distinct Letter](./solutions/1180-count-substrings-with-only-one-distinct-letter.js)|Easy|
1106+
1181|[Before and After Puzzle](./solutions/1181-before-and-after-puzzle.js)|Medium|
11061107
1184|[Distance Between Bus Stops](./solutions/1184-distance-between-bus-stops.js)|Easy|
11071108
1185|[Day of the Week](./solutions/1185-day-of-the-week.js)|Easy|
11081109
1186|[Maximum Subarray Sum with One Deletion](./solutions/1186-maximum-subarray-sum-with-one-deletion.js)|Medium|
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* 1181. Before and After Puzzle
3+
* https://leetcode.com/problems/before-and-after-puzzle/
4+
* Difficulty: Medium
5+
*
6+
* Given a list of phrases, generate a list of Before and After puzzles.
7+
*
8+
* A phrase is a string that consists of lowercase English letters and spaces only. No
9+
* space appears in the start or the end of a phrase. There are no consecutive spaces
10+
* in a phrase.
11+
*
12+
* Before and After puzzles are phrases that are formed by merging two phrases where the
13+
* last word of the first phrase is the same as the first word of the second phrase.
14+
*
15+
* Return the Before and After puzzles that can be formed by every two phrases phrases[i]
16+
* and phrases[j] where i != j. Note that the order of matching two phrases matters, we
17+
* want to consider both orders.
18+
*
19+
* You should return a list of distinct strings sorted lexicographically.
20+
*/
21+
22+
/**
23+
* @param {string[]} phrases
24+
* @return {string[]}
25+
*/
26+
var beforeAndAfterPuzzles = function(phrases) {
27+
const set = new Set();
28+
29+
for (let i = 0; i < phrases.length; i++) {
30+
for (let j = 0; j < phrases.length; j++) {
31+
if (i !== j) {
32+
const firstWords = phrases[i].split(' ');
33+
const secondWords = phrases[j].split(' ');
34+
35+
const lastWordFirst = firstWords[firstWords.length - 1];
36+
const firstWordSecond = secondWords[0];
37+
if (lastWordFirst === firstWordSecond) {
38+
const merged = firstWords.concat(secondWords.slice(1)).join(' ');
39+
set.add(merged);
40+
}
41+
}
42+
}
43+
}
44+
45+
return Array.from(set).sort();
46+
};

0 commit comments

Comments
 (0)