Skip to content

Commit

Permalink
Create 0139-word-break.kt
Browse files Browse the repository at this point in the history
  • Loading branch information
a93a committed Dec 29, 2022
1 parent 324cd74 commit 005ecd9
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions kotlin/0139-word-break.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
class Solution {
fun wordBreak(s: String, wordDict: List<String>): Boolean {
val cache = BooleanArray(s.length+1)
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)
for(i in s.length-1 downTo 0){
for(word in wordDict){
if(word.length+i <= s.length){//enough chars in s for this word to be viable ?
if(word == s.substring(i, i+word.length)){// its the same word char by char?
if(cache[i+word.length] == true) //this cache index is true only if the cache at index [i+word.length is true]
cache[i] = true
}
}
}
}
return cache[0]
}
}

0 comments on commit 005ecd9

Please sign in to comment.