Skip to content

Commit a2524c2

Browse files
authored
Update 472-concatenated-words.js
1 parent 87d3fde commit a2524c2

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

472-concatenated-words.js

+38
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,44 @@ const findAllConcatenatedWordsInADict = function (words) {
3333
}
3434
}
3535

36+
// another
37+
38+
/**
39+
* @param {string[]} words
40+
* @return {string[]}
41+
*/
42+
43+
const findAllConcatenatedWordsInADict = function (words) {
44+
const set = new Set(words)
45+
const res = []
46+
const map = new Map()
47+
48+
for(let word of words) {
49+
if(dfs(word, 0)) res.push(word)
50+
}
51+
return res
52+
function dfs(word, idx) {
53+
if(map.has(word)) return map.get(word)
54+
if(idx > 0 && set.has(word)) return true
55+
let tmp = false
56+
for(let i = 1; i < word.length; i++) {
57+
const prefix = word.slice(0, i), suffix = word.slice(i)
58+
if(set.has(prefix) && set.has(suffix)) {
59+
tmp = true
60+
break
61+
}
62+
if(set.has(prefix) && dfs(suffix, idx + 1)) {
63+
tmp = true
64+
break
65+
}
66+
}
67+
68+
map.set(word, tmp)
69+
return tmp
70+
}
71+
}
72+
73+
3674
// another
3775

3876
/**

0 commit comments

Comments
 (0)