Skip to content

Commit a923ce5

Browse files
authored
Update 0139-word-break.kt
1 parent b17b980 commit a923ce5

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

kotlin/0139-word-break.kt

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,3 +46,41 @@ class Solution {
4646
return if (dfs(0) == 1) true else false
4747
}
4848
}
49+
50+
//trie
51+
class Solution {
52+
53+
class TrieNode {
54+
val child = arrayOfNulls<TrieNode>(26)
55+
var isEnd = false
56+
}
57+
58+
fun wordBreak(s: String, wordDict: List<String>): Boolean {
59+
var root: TrieNode? = TrieNode()
60+
61+
for (word in wordDict) {
62+
var cur = root
63+
for (c in word) {
64+
if(cur?.child?.get(c - 'a') == null)
65+
cur?.child?.set(c - 'a', TrieNode())
66+
cur = cur?.child?.get(c - 'a')
67+
}
68+
cur?.isEnd = true
69+
}
70+
71+
val dp = BooleanArray (s.length + 1).apply { this[0] = true }
72+
73+
for (i in 0 until s.length) {
74+
if (dp[i] == false) continue
75+
var j = i
76+
var cur = root
77+
while (j < s.length && cur?.child?.get(s[j] - 'a') != null) {
78+
cur = cur?.child?.get(s[j++] - 'a')
79+
if (cur?.isEnd == true)
80+
dp[j] = true
81+
}
82+
}
83+
84+
return dp[s.length]
85+
}
86+
}

0 commit comments

Comments
 (0)