forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0472-concatenated-words.kt
More file actions
31 lines (26 loc) · 905 Bytes
/
0472-concatenated-words.kt
File metadata and controls
31 lines (26 loc) · 905 Bytes
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
class Solution {
fun findAllConcatenatedWordsInADict(words: Array<String>): List<String> {
val wordSet = words.toSet()
val dp = HashMap<String, Boolean>()
fun dfs(word: String): Boolean {
if (word in dp) return dp[word]!!
for (i in 1 until word.length) {
val prefix = word.substring(0, i)
val suffix = word.substring(i, word.length)
if ((prefix in wordSet && suffix in wordSet) ||
prefix in wordSet && dfs(suffix)) {
dp[word] = true
return true
}
}
dp[word] = false
return false
}
var res = mutableListOf<String>()
for (word in words) {
if (dfs(word))
res.add(word)
}
return res
}
}