Skip to content

Commit 8d9ab23

Browse files
authored
Create 0010-regular-expression-matching.kt
1 parent 7ef654d commit 8d9ab23

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
//dp
2+
class Solution {
3+
fun isMatch(s: String, p: String): Boolean {
4+
val dp = Array (s.length + 1) { BooleanArray (p.length + 1) }
5+
dp[0][0] = true
6+
7+
for (i in 0..s.length) {
8+
for (j in 1..p.length) {
9+
if (p[j - 1] == '*') {
10+
dp[i][j] = dp[i][j - 2] || (i > 0 && dp[i - 1][j] && (s[i - 1] == p[j - 2] || p[j - 2] == '.'))
11+
} else {
12+
dp[i][j] = i > 0 && dp[i - 1][j - 1] && (s[i - 1] == p[j - 1] || p[j - 1] == '.')
13+
}
14+
}
15+
}
16+
17+
return dp[s.length][p.length]
18+
}
19+
}
20+
21+
//recursion + memoization
22+
class Solution {
23+
fun isMatch(s: String, p: String): Boolean {
24+
val cache = Array (s.length + 1) { IntArray (p.length + 1) { -1 } }
25+
26+
fun dfs(i: Int, j: Int): Int {
27+
if (i >= s.length && j >= p.length)
28+
return 1
29+
if (j >= p.length)
30+
return 0
31+
if (cache[i][j] != -1)
32+
return cache[i][j]
33+
34+
val charMatched = i < s.length && (s[i] == p[j] || p[j] == '.')
35+
36+
if (j + 1 < p.length && p[j + 1] == '*')
37+
return if (dfs(i, j + 2) == 1 || charMatched && dfs(i + 1, j) == 1) 1 else 0
38+
if (charMatched)
39+
return dfs(i + 1, j + 1)
40+
41+
cache[i][j] == 0
42+
return 0
43+
}
44+
45+
return dfs(0, 0) == 1
46+
}
47+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy