Skip to content

Commit 162931c

Browse files
authored
Merge pull request neetcode-gh#1722 from simhonchourasia/add0010
Create 0010-regular-expression-matching.go
2 parents 4d45871 + ce2bee4 commit 162931c

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
func isMatch(s string, p string) bool {
2+
// dp[i][j] is true if p[:i] matches s[:j]
3+
dp := make([][]bool, len(p) + 1)
4+
for i := 0; i < len(p) + 1; i++ {
5+
dp[i] = make([]bool, len(s) + 1)
6+
for j := 0; j < len(s) + 1; j++ {
7+
dp[i][j] = false
8+
}
9+
}
10+
11+
dp[0][0] = true
12+
13+
// Base case for i = 0 is already set up, as empty pattern can only match empty string
14+
// But a nonempty pattern can match an empty string, so we do base cases for j = 0
15+
for i := 1; i < len(p); i++ {
16+
if p[i] == '*' {
17+
dp[i + 1][0] = dp[i - 1][0]
18+
}
19+
}
20+
21+
// Now for the general case
22+
for i := 0; i < len(p); i++ {
23+
for j := 0; j < len(s); j++ {
24+
if p[i] == '.' || p[i] == s[j] {
25+
// Single character matches
26+
dp[i + 1][j + 1] = dp[i][j]
27+
} else if p[i] == '*' {
28+
// Wildcard - check that the character matches
29+
// or if we can have 0 repetitions of the previous char
30+
dp[i + 1][j + 1] = dp[i - 1][j + 1] || dp[i][j + 1]
31+
if p[i - 1] == '.' || p[i - 1] == s[j] {
32+
if dp[i + 1][j] {
33+
dp[i + 1][j + 1] = dp[i + 1][j]
34+
}
35+
}
36+
}
37+
}
38+
}
39+
40+
return dp[len(p)][len(s)]
41+
}

0 commit comments

Comments
 (0)