File tree Expand file tree Collapse file tree 1 file changed +31
-21
lines changed
solution/0000-0099/0010.Regular Expression Matching Expand file tree Collapse file tree 1 file changed +31
-21
lines changed Original file line number Diff line number Diff line change 1- bool isMatch (char * s , char * p ) {
2- int m = strlen (s ), n = strlen (p );
3- bool * * dp = malloc ((m + 1 ) * sizeof (bool * ));
4- for (int i = 0 ; i <= m ; i ++ )
5- dp [i ] = calloc (n + 1 , sizeof (bool ));
6- dp [0 ][0 ] = 1 ;
7- for (int j = 2 ; j <= n ; j ++ )
8- if (p [j - 1 ] == '*' )
9- dp [0 ][j ] = dp [0 ][j - 2 ];
1+ #define MAX_LEN 1000
2+
3+ char * ss , * pp ;
4+ int m , n ;
5+ int f [MAX_LEN + 1 ][MAX_LEN + 1 ];
106
11- for (int i = 1 ; i <= m ; i ++ )
12- for (int j = 1 ; j <= n ; j ++ )
13- if (p [j - 1 ] == '*' )
14- dp [i ][j ] = dp [i ][j - 2 ] || ((p [j - 2 ] == '.' || p [j - 2 ] == s [i - 1 ]) && dp [i - 1 ][j ]);
15- else
16- dp [i ][j ] = (p [j - 1 ] == '.' || p [j - 1 ] == s [i - 1 ]) && dp [i - 1 ][j - 1 ];
7+ bool dfs (int i , int j ) {
8+ if (j >= n ) {
9+ return i == m ;
10+ }
11+ if (f [i ][j ] != 0 ) {
12+ return f [i ][j ] == 1 ;
13+ }
14+ int res = -1 ;
15+ if (j + 1 < n && pp [j + 1 ] == '*' ) {
16+ if (dfs (i , j + 2 ) || (i < m && (ss [i ] == pp [j ] || pp [j ] == '.' ) && dfs (i + 1 , j ))) {
17+ res = 1 ;
18+ }
19+ } else if (i < m && (ss [i ] == pp [j ] || pp [j ] == '.' ) && dfs (i + 1 , j + 1 )) {
20+ res = 1 ;
21+ }
22+ f [i ][j ] = res ;
23+ return res == 1 ;
24+ }
1725
18- bool res = dp [m ][n ];
19- for (int i = 0 ; i <= m ; i ++ )
20- free (dp [i ]);
21- free (dp );
22- return res ;
23- }
26+ bool isMatch (char * s , char * p ) {
27+ ss = s ;
28+ pp = p ;
29+ m = strlen (s );
30+ n = strlen (p );
31+ memset (f , 0 , sizeof (f ));
32+ return dfs (0 , 0 );
33+ }
You can’t perform that action at this time.
0 commit comments