Skip to content

Commit 19ac281

Browse files
authored
Create 0097-interleaving-string.kt
1 parent 83efc29 commit 19ac281

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

kotlin/0097-interleaving-string.kt

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
//DP
2+
class Solution {
3+
fun isInterleave(s1: String, s2: String, s3: String): Boolean {
4+
5+
val dp = Array(s1.length + 1) { BooleanArray(s2.length + 1) }
6+
val n = s1.length
7+
val m = s2.length
8+
9+
if(n + m != s3.length) return false
10+
11+
dp[n][m] = true
12+
13+
for (i in n downTo 0) {
14+
for (j in m downTo 0) {
15+
if (i < n && s1[i] == s3[i+j] && dp[i + 1][j])
16+
dp[i][j] = true
17+
if (j < m && s2[j] == s3[i+j] && dp[i][j + 1])
18+
dp[i][j] = true
19+
}
20+
}
21+
22+
return dp[0][0]
23+
}
24+
}
25+
26+
//DFS with memoization
27+
class Solution {
28+
fun isInterleave(s1: String, s2: String, s3: String): Boolean {
29+
30+
if(s1.length + s2.length != s3.length) return false
31+
32+
val memo = Array(s1.length + 1) { BooleanArray(s2.length + 1) }
33+
val n = s1.length
34+
val m = s2.length
35+
36+
fun dfs(i: Int, j: Int): Boolean {
37+
38+
if (i == n && j == m) return true
39+
if (memo[i][j] == true) return false
40+
41+
if (i < n && s1[i] == s3[i+j]) {
42+
if (dfs(i + 1, j))
43+
return true
44+
}
45+
if (j < m && s2[j] == s3[i+j]) {
46+
if (dfs(i, j + 1))
47+
return true
48+
}
49+
50+
memo[i][j] = true
51+
return false
52+
}
53+
54+
return dfs(0,0)
55+
}
56+
}

0 commit comments

Comments
 (0)