Skip to content

Commit b17b980

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

File tree

1 file changed

+38
-7
lines changed

1 file changed

+38
-7
lines changed

kotlin/0139-word-break.kt

Lines changed: 38 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
1+
//DP
12
class Solution {
23
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]
4+
val cache = BooleanArray (s.length + 1).apply {
5+
this[s.length] = true
6+
}
7+
8+
for (i in s.lastIndex downTo 0) {
9+
for (word in wordDict) {
10+
if (word.length + i <= s.length) {
11+
if (word == s.substring(i, i + word.length)) {
12+
if (cache[i + word.length] == true)
1013
cache[i] = true
1114
}
1215
}
@@ -15,3 +18,31 @@ class Solution {
1518
return cache[0]
1619
}
1720
}
21+
22+
//Recursive + memoization
23+
class Solution {
24+
fun wordBreak(s: String, wordDict: List<String>): Boolean {
25+
val cache = IntArray (s.length + 1) { -1 }
26+
27+
fun dfs(i: Int): Int {
28+
if (i == s.length) return 1
29+
if (cache[i] != -1) return cache[i]
30+
31+
cache[i] = 0
32+
33+
for (word in wordDict) {
34+
if (word.length + i <= s.length &&
35+
word == s.substring(i, i + word.length)) {
36+
if (dfs(i + word.length) == 1) {
37+
cache[i] = 1
38+
return 1
39+
}
40+
}
41+
}
42+
43+
return 0
44+
}
45+
46+
return if (dfs(0) == 1) true else false
47+
}
48+
}

0 commit comments

Comments
 (0)