-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0472--concatenated-words.js
82 lines (68 loc) · 2.32 KB
/
0472--concatenated-words.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Given an array of strings words (without duplicates),
// return all the concatenated words in the given list of words.
// A concatenated word is defined as a string that is comprised entirely of at least
// two shorter words in the given array.
// --- Examples
// Input: words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]
// Output: ["catsdogcats","dogcatsdog","ratcatdogcat"]
// Explanation: "catsdogcats" can be concatenated by "cats", "dog" and "cats";
// "dogcatsdog" can be concatenated by "dog", "cats" and "dog";
// "ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat".
// Input: words = ["cat","dog","catdog"]
// Output: ["catdog"]
// --- Constraints
// 1 <= words.length <= 104
// 1 <= words[i].length <= 30
// words[i] consists of only lowercase English letters.
// All the strings of words are unique.
// 1 <= sum(words[i].length) <= 105
/**
* @param {string[]} words
* @return {string[]}
*/
const findAllConcatenatedWordsInADict = function (words) {
const dictionary = new Set(words);
const concatenatedWords = [];
for (const word of words) {
const dp = Array(word.length + 1).fill(false);
dp[0] = true;
for (let endIndex = 1; endIndex <= word.length; endIndex++) {
for (
let startIndex = 0;
!dp[endIndex] && startIndex < endIndex;
startIndex++
) {
// to avoid comparing the word to itself, skip the iteration if start === 0 && end === word.length
if (startIndex === 0 && endIndex === word.length) continue;
dp[endIndex] =
dp[startIndex] && dictionary.has(word.slice(startIndex, endIndex));
}
}
if (dp[word.length]) concatenatedWords.push(word);
}
return concatenatedWords;
};
/**
* @param {string[]} words
* @return {string[]}
*/
const findAllConcatenatedWordsInADictDFS = (words) => {
const dictionary = new Set(words);
const concatenatedWords = [];
for (const word of words) {
if (isConcat(word)) concatenatedWords.push(word);
}
return concatenatedWords;
function isConcat(word) {
for (let i = 1; i < word.length; i++) {
const prefix = word.slice(0, i);
const suffix = word.slice(i);
if (
dictionary.has(prefix) &&
(dictionary.has(suffix) || isConcat(suffix))
)
return true;
}
return false;
}
};