Skip to content

Commit 7c719aa

Browse files
committedFeb 16, 2025
Add solution #472
1 parent 5684fe8 commit 7c719aa

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -277,6 +277,7 @@
277277
459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy|
278278
461|[Hamming Distance](./0461-hamming-distance.js)|Easy|
279279
463|[Island Perimeter](./0463-island-perimeter.js)|Medium|
280+
472|[Concatenated Words](./0472-concatenated-words.js)|Hard|
280281
476|[Number Complement](./0476-number-complement.js)|Easy|
281282
482|[License Key Formatting](./0482-license-key-formatting.js)|Easy|
282283
485|[Max Consecutive Ones](./0485-max-consecutive-ones.js)|Easy|

‎solutions/0472-concatenated-words.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* 472. Concatenated Words
3+
* https://leetcode.com/problems/concatenated-words/
4+
* Difficulty: Hard
5+
*
6+
* Given an array of strings words (without duplicates), return all the concatenated words
7+
* in the given list of words.
8+
*
9+
* A concatenated word is defined as a string that is comprised entirely of at least two
10+
* shorter words (not necessarily distinct) in the given array.
11+
*/
12+
13+
/**
14+
* @param {string[]} words
15+
* @return {string[]}
16+
*/
17+
var findAllConcatenatedWordsInADict = function(words) {
18+
const set = new Set(words);
19+
const map = new Map();
20+
21+
function isValid(word) {
22+
if (map.has(word)) return map.get(word);
23+
for (let i = 1; i < word.length; i++) {
24+
const suffix = word.slice(i);
25+
if (set.has(word.slice(0, i)) && (set.has(suffix) || isValid(suffix))) {
26+
map.set(word, true);
27+
return true;
28+
}
29+
}
30+
map.set(word, false);
31+
return false;
32+
}
33+
34+
return words.filter(word => word.length > 0 && isValid(word));
35+
};

0 commit comments

Comments
 (0)
Please sign in to comment.