Skip to content

Commit 472e208

Browse files
committed
Improved task 10.
1 parent 8e1bac5 commit 472e208

File tree

1 file changed

+28
-19
lines changed
  • src/main/kotlin/g0001_0100/s0010_regular_expression_matching

1 file changed

+28
-19
lines changed
Lines changed: 28 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,28 @@
1-
package g0001_0100.s0010_regular_expression_matching
2-
3-
class Solution {
4-
fun isMatch(text: String, pattern: String): Boolean {
5-
val dp = Array(text.length + 1) { BooleanArray(pattern.length + 1) }
6-
dp[text.length][pattern.length] = true
7-
for (i in text.length downTo 0) {
8-
for (j in pattern.length - 1 downTo 0) {
9-
val firstMatch = i < text.length && (pattern[j] == text[i] || pattern[j] == '.')
10-
if (j + 1 < pattern.length && pattern[j + 1] == '*') {
11-
dp[i][j] = dp[i][j + 2] || firstMatch && dp[i + 1][j]
12-
} else {
13-
dp[i][j] = firstMatch && dp[i + 1][j + 1]
14-
}
15-
}
16-
}
17-
return dp[0][0]
18-
}
19-
}
1+
package g0001_0100.s0010_regular_expression_matching
2+
3+
class Solution {
4+
private lateinit var cache: Array<Array<Boolean?>>
5+
6+
fun isMatch(s: String, p: String): Boolean {
7+
cache = Array(s.length + 1) { arrayOfNulls(p.length + 1) }
8+
return isMatch(s, p, 0, 0)
9+
}
10+
11+
private fun isMatch(s: String, p: String, i: Int, j: Int): Boolean {
12+
if (j == p.length) {
13+
return i == s.length
14+
}
15+
val result: Boolean
16+
if (cache[i][j] != null) {
17+
return cache[i][j]!!
18+
}
19+
val firstMatch = i < s.length && (s[i] == p[j] || p[j] == '.')
20+
result = if (j + 1 < p.length && p[j + 1] == '*') {
21+
firstMatch && isMatch(s, p, i + 1, j) || isMatch(s, p, i, j + 2)
22+
} else {
23+
firstMatch && isMatch(s, p, i + 1, j + 1)
24+
}
25+
cache[i][j] = result
26+
return result
27+
}
28+
}

0 commit comments

Comments
 (0)