Just recently learning compiler theory
A bit like writing in accordance with the parsing. . But no need to
Knowing regular expressions There are several possible methods for matching a string, so be ready to go back.
There optimal substructure, from a length of a period p s generation, thus dp.
Conventional thinking is beginning to match the previous character by character
Here Think less case backwards matching consider some (actually wanted to write a positive discovered too hard ... embarrassing)
dp [i] [j] represents the s [i:] may be formed of p [j:] (. matches) generates so they only need to consider matching 0-i-1,0-j-1 is
match a specific character formula (x or., but not *) and a character string matching a
As s = abbb, p = ab *
bbb and b * matches, are associated with each of a and b * b b match match.
If the match only two cases a single. X * match and match.
Specific treatment
A single matching dp [i] [j] = first_match && dp [i + 1] [j + 1]; // possible match to (match == true), then advancing a
x * matches dp [i] [j] = dp [i] [j + 2] || match && dp [i + 1] [j]; // both cases, may be used p [j], the mismatched , dp [i] [j] = dp [i] [j + 2]; or may match, dp [i] [j] = dp [i + 1] [j], a character propulsion (i + 1 )
Official explanations complexity analysis to see it
Note Initialization
Do not add false initialization
Running an example
dp[i][j] = match && dp[i+1][j+1];
class Solution { public: bool isMatch(string s, string p) { bool dp[s.length() + 1][p.length() + 1]; for(int i=0;i<=s.length();i++) for(int j=0;j<=p.length();j++) dp[i][j]=false; dp[s.length()][p.length()] = true; for (int i = s.length(); i >= 0; i--){ for (int j = p.length() - 1; j >= 0; j--){ bool match = (i < s.length() &&(p[j] == s[i] ||p[j] == '.')); if (j + 1 < p.length() && p[j+1] == '*'){ //x*匹配 dp[i][j] = dp[i][j+2] || match && dp[i+1][j]; } else { //单个.匹配 dp[i][j] = match && dp[i+1][j+1]; } } } return dp[0][0]; } };