Skip to content

Commit 07718d5

Browse files
authored
Update 472-concatenated-words.js
1 parent a2524c2 commit 07718d5

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

472-concatenated-words.js

+41
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,44 @@
1+
/**
2+
* @param {string[]} words
3+
* @return {string[]}
4+
*/
5+
6+
const findAllConcatenatedWordsInADict = function (words) {
7+
const pre = new Set()
8+
words.sort((a, b) => a.length - b.length)
9+
const res = []
10+
for(let i = 0; i < words.length; i++) {
11+
if(valid(words[i], pre)) {
12+
res.push(words[i])
13+
}
14+
pre.add(words[i])
15+
}
16+
17+
return res
18+
19+
function valid(str, set) {
20+
if(set.size === 0) return false
21+
const dp = Array(str.length + 1).fill(false)
22+
dp[0] = true
23+
for(let i = 1; i <= str.length; i++) {
24+
for(let j = 0; j < i; j++) {
25+
if(!dp[j]) continue
26+
if(set.has(str.slice(j, i))) {
27+
dp[i] = true
28+
break
29+
}
30+
}
31+
}
32+
33+
return dp[str.length]
34+
}
35+
}
36+
37+
38+
39+
40+
// another
41+
142
/**
243
* @param {string[]} words
344
* @return {string[]}

0 commit comments

Comments
 (0)