Skip to content

Commit 005ecd9

Browse files
committed
Create 0139-word-break.kt
1 parent 324cd74 commit 005ecd9

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

kotlin/0139-word-break.kt

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution {
2+
fun wordBreak(s: String, wordDict: List<String>): Boolean {
3+
val cache = BooleanArray(s.length+1)
4+
cache[s.length] = true // lastPos is true, meaning [array of word length], lastPos] since string "" can be segmented of any list of any words (our dp basecase)
5+
for(i in s.length-1 downTo 0){
6+
for(word in wordDict){
7+
if(word.length+i <= s.length){//enough chars in s for this word to be viable ?
8+
if(word == s.substring(i, i+word.length)){// its the same word char by char?
9+
if(cache[i+word.length] == true) //this cache index is true only if the cache at index [i+word.length is true]
10+
cache[i] = true
11+
}
12+
}
13+
}
14+
}
15+
return cache[0]
16+
}
17+
}

0 commit comments

Comments
 (0)