1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| class Solution { int dp[21][31]; bool dfs(string & s, string & p, int sp, int pp) { if(dp[sp][pp] != -1) return dp[sp][pp]; if(sp == s.length()) { if(pp != p.length() - 1 and p[pp + 1] == '*') return dp[sp][pp] = dfs(s, p, sp, pp+2); return dp[sp][pp] = 0; } if(pp == p.length() - 1) { if(s[sp] == p[pp] || p[pp] == '.') return dp[sp][pp] = dfs(s,p,sp + 1, pp + 1); return dp[sp][pp] = 0; } if(p[pp + 1] == '*') { dp[sp][pp] = dfs(s,p,sp,pp+2); if(p[pp] == '.') { for(int i = sp; i < s.length(); i++) dp[sp][pp] |= dfs(s,p,i+1,pp+2); } else { dp[sp][pp] = dfs(s,p,sp,pp+2); for(int i = sp; i < s.length() and s[i] == p[pp]; i++) dp[sp][pp] |= dfs(s,p,i+1,pp+2); } return dp[sp][pp]; } if(p[pp] == '.') return dp[sp][pp] = dfs(s, p, sp + 1, pp + 1);; if(s[sp] != p[pp]) return dp[sp][pp] = 0; return dp[sp][pp] = dfs(s,p,sp + 1, pp + 1); } public: bool isMatch(string s, string p) { memset(dp,-1,sizeof(dp)); for(int i = 0; i < s.length(); i++) dp[i][p.length()] = 0; dp[s.length()][p.length()] = 1; dfs(s, p, 0, 0); return dp[0][0]; } };
|