Skip to content

Commit 187694f

Browse files
committed
Add solution #648
1 parent b6f60d1 commit 187694f

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium|
1717
606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy|
1818
617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy|
19+
648|[Replace Words](./0648-replace-words.js)|Medium|
1920
739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium|
2021
791|[Custom Sort String](./0791-custom-sort-string.js)|Medium|
2122
804|[Unique Morse Code Words](./0804-unique-morse-code-words.js)|Easy|

solutions/0648-replace-words.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* 648. Replace Words
3+
* https://leetcode.com/problems/replace-words/
4+
* Difficulty: Medium
5+
*
6+
* In English, we have a concept called root, which can be followed by some other words
7+
* to form another longer word - let's call this word successor. For example, the root
8+
* an, followed by other, which can form another word another.
9+
*
10+
* Now, given a dictionary consisting of many roots and a sentence. You need to replace
11+
* all the successor in the sentence with the root forming it. If a successor has many
12+
* roots can form it, replace it with the root with the shortest length.
13+
*
14+
* You need to output the sentence after the replacement.
15+
*/
16+
17+
/**
18+
* @param {string[]} dict
19+
* @param {string} sentence
20+
* @return {string}
21+
*/
22+
var replaceWords = function(dict, sentence) {
23+
const set = new Set(dict);
24+
return sentence.split(/\s+/).map(word => {
25+
for (let i = 1; i <= word.length; i++) {
26+
if (set.has(word.slice(0, i))) return word.slice(0, i);
27+
}
28+
return word;
29+
}).join(' ');
30+
};

0 commit comments

Comments
 (0)