# 【动态规划】正则表达式匹配

【题目链接】：

https://www.acwing.com/problem/content/28/

【题目解释】

#### 样例

输入：

s="aa"
p="a*"

#### 【参考】y总的视频讲解。

 1 /*
2 s="aa"
3 p="a*"
4
5 f[i][j] 指的是: s[i,...] p[j,...] 相匹配
6
7 1. 当p[i] 是正常的字符 , s[i] == p[j] , f[i][j] = f[i+1][j+1]
8 2. 当p[i] = '.' ,  f[i][j] = f[i+1][j+1]
9 3. 当p[i+1] = '*' ,f[i][j] = f[i][j+2] || f[i+1][j]
10
11
12 边界问题 : f[n][m] = true;
13 */
14
15
16
17 class Solution {
18 public:
19     string s , p  ;
20     vector< vector<int > > f ;
21     int n, m ;
22     bool isMatch(string _s, string _p) {
23         s = _s , p = _p ;
24         n = s.length() , m = p.length() ;
25         f = vector<vector<int>>( n+2 , vector<int> ( m+2 , -1 ) );
26         return dp(0,0);
27     }
28     bool dp(int x,int y){
29         if( f[x][y] != -1 ) return f[x][y] ;
30         if( y == m )    return (f[x][y] = (x==n));
31         bool First = (x < n && (p[y] == '.' || s[x] == p[y]) ) ;
32
33         if( y+1 < m && p[y+1] == '*' ){
34             f[x][y] = dp(x,y+2) || First && dp(x+1,y);
35         }else{
36             f[x][y] =  First && dp(x+1,y+1);
37         }
38         return f[x][y];
39     }
40 };

 
posted @ 2019-08-20 02:19 Osea 阅读(...) 评论(...) 编辑 收藏