Skip to content

Commit f94c7e6

Browse files
committed
add problem 10 - Regular Expression Matching
1 parent 41825b9 commit f94c7e6

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package dynamic_programming
2+
3+
func RegularExpressionMatching(s string, p string) bool {
4+
// Length of strings
5+
m, n := len(s), len(p)
6+
// Lookup table to store if s[0...i] matches p[0...j]
7+
lookup := make([][]bool, m+1)
8+
for i := range lookup {
9+
lookup[i] = make([]bool, n+1)
10+
for j := range lookup[i] {
11+
lookup[i][j] = false
12+
}
13+
}
14+
// Empty string matches with empty patten
15+
lookup[0][0] = true
16+
// For empty string and star pattern
17+
for j := 2; j <= n; j++ {
18+
if p[j-1] == '*' {
19+
lookup[0][j] = lookup[0][j-2]
20+
}
21+
}
22+
// Populate remaining table
23+
for i := 1; i <= m; i++ {
24+
for j := 1; j <= n; j++ {
25+
// If characters are same or pattern is period
26+
if s[i-1] == p[j-1] || p[j-1] == '.' {
27+
lookup[i][j] = lookup[i-1][j-1]
28+
} else if j > 1 && p[j-1] == '*' {
29+
lookup[i][j] = lookup[i][j-2]
30+
if p[j-2] == '.' || p[j-2] == s[i-1] {
31+
lookup[i][j] = lookup[i][j] || lookup[i-1][j]
32+
}
33+
}
34+
}
35+
}
36+
return lookup[m][n]
37+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package dynamic_programming_test
2+
3+
import (
4+
"testing"
5+
6+
"github.com/anirudhology/leetcode-go/problems/dynamic_programming"
7+
)
8+
9+
func TestIsMatch(t *testing.T) {
10+
tests := []struct {
11+
s, p string
12+
result bool
13+
}{
14+
{"aa", "a*", true},
15+
{"ab", ".*", true},
16+
{"mississippi", "mis*is*p*.", false},
17+
{"aab", "c*a*b", true},
18+
{"ab", "a", false},
19+
{"", ".*", true},
20+
{"", "a*", true},
21+
{"abcd", "d*", false},
22+
{"aaa", "a*a", true},
23+
{"aaa", "ab*a", false},
24+
}
25+
26+
for _, test := range tests {
27+
if got := dynamic_programming.RegularExpressionMatching(test.s, test.p); got != test.result {
28+
t.Errorf("isMatch(%v, %v) = %v; want %v", test.s, test.p, got, test.result)
29+
}
30+
}
31+
}

0 commit comments

Comments
 (0)