File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change @@ -46,3 +46,41 @@ class Solution {
46
46
return if (dfs(0 ) == 1 ) true else false
47
47
}
48
48
}
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
+ }
You can’t perform that action at this time.
0 commit comments