File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed
Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments