|
| 1 | +/* |
| 2 | + * @lc app=leetcode.cn id=10 lang=cpp |
| 3 | + * |
| 4 | + * [10] 正则表达式匹配 |
| 5 | + */ |
| 6 | + |
| 7 | +// @lc code=start |
| 8 | +#include<iostream> |
| 9 | +#include<string> |
| 10 | + |
| 11 | +using namespace std; |
| 12 | + |
| 13 | +class Solution { |
| 14 | +public: |
| 15 | + bool isMatch(string s, string p) { |
| 16 | + // return doMatch(s, p, 0, 0); |
| 17 | + memset(memo, 0, sizeof(memo)); |
| 18 | + return state(s, p, 0, 0); |
| 19 | + } |
| 20 | + |
| 21 | + // bool doMatch(string &s, string &p, int s_pos, int p_pos) |
| 22 | + // { |
| 23 | + // if(p_pos>=p.size())return s_pos>=s.size(); |
| 24 | + // bool currentMatch = s_pos<s.size() && (s[s_pos]==p[p_pos] || p[p_pos]=='.'); |
| 25 | + // if(p_pos<p.size()-1 && p[p_pos+1]=='*') |
| 26 | + // { |
| 27 | + // return doMatch(s,p,s_pos,p_pos+2)||(doMatch(s,p,s_pos+1,p_pos)&¤tMatch); |
| 28 | + // } |
| 29 | + // else{ |
| 30 | + // return currentMatch && doMatch(s, p, s_pos+1, p_pos+1); |
| 31 | + // } |
| 32 | + // } |
| 33 | + |
| 34 | + int memo[1000][1000]; |
| 35 | + bool state(string &s, string &p, int s_pos, int p_pos) |
| 36 | + { |
| 37 | + |
| 38 | + bool ans = false; |
| 39 | + if(s_pos==s.size() && p_pos>=p.size()) return true; |
| 40 | + |
| 41 | + if(s_pos!=s.size() && p_pos==p.size())return false; |
| 42 | + |
| 43 | + if(memo[s_pos][p_pos]!=0)return memo[s_pos][p_pos] == 2; |
| 44 | + if(p_pos<p.size()-1 && p[p_pos+1] == '*'){ |
| 45 | + if(s[s_pos] == p[p_pos] || (p[p_pos]=='.' && s_pos!=s.size())){ |
| 46 | + ans = state(s, p, s_pos+1, p_pos) || state(s, p, s_pos, p_pos+2); |
| 47 | + }else |
| 48 | + { |
| 49 | + ans = state(s, p, s_pos, p_pos+2); |
| 50 | + } |
| 51 | + } |
| 52 | + else if((p[p_pos]=='.' && s_pos<s.size()) || s[s_pos]==p[p_pos]) |
| 53 | + ans = state(s, p, s_pos+1, p_pos+1); |
| 54 | + |
| 55 | + memo[s_pos][p_pos] = int(ans) + 1; |
| 56 | + return ans; |
| 57 | + } |
| 58 | + |
| 59 | +}; |
| 60 | +// @lc code=end |
| 61 | + |
0 commit comments