File tree 2 files changed +31
-0
lines changed
2 files changed +31
-0
lines changed Original file line number Diff line number Diff line change 16
16
451|[ Sort Characters By Frequency] ( ./0451-sort-characters-by-frequency.js ) |Medium|
17
17
606|[ Construct String from Binary Tree] ( ./0606-construct-string-from-binary-tree.js ) |Easy|
18
18
617|[ Merge Two Binary Trees] ( ./0617-merge-two-binary-trees.js ) |Easy|
19
+ 648|[ Replace Words] ( ./0648-replace-words.js ) |Medium|
19
20
739|[ Daily Temperatures] ( ./0739-daily-temperatures.js ) |Medium|
20
21
791|[ Custom Sort String] ( ./0791-custom-sort-string.js ) |Medium|
21
22
804|[ Unique Morse Code Words] ( ./0804-unique-morse-code-words.js ) |Easy|
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments