The following question numbers are Leetcode, which makes it easy to view the original problem.
Ten. Regular Expression Matching
Test instructions: Implements a regular Match of strings, containing '. ' and ' * '. '. ' matches any one character, "*" matches 0 or more characters prior to ' * '.
Example
false IsMatch (trueIsMatch (falseIsMatch (trueisMatch ( true IsMatch (trueisMatch (true
Idea: Input string s[0...m] and P[0...N]
F[I][J] for s[0..i-1] and p[0..j-1] matches, we need to determine if s and p match, that is, the value of F[m][n] is true, so we want to update the value of F[i][j].
Update ideas as follows:
1, if p[j-1]!= ' * ', f[i][j] = f[i-1][j-1] & (S[i-1]==p[j-1] | | p[j-1]== '. ')
2, if p[j-1]== ' * ', see ' * ' match how many characters, that is to match how many p[j-2].
If ' * ' matches 0 characters, at this time, p[0...j-1]==p[0...j-3],f[i][j]=f[i][j-2];
If ' * ' matches 1 characters, at this time, p[0...j-1]==p[0...j-2],f[i][j]=f[i][j-1];
If ' * ' matches multiple characters, at this time, p[0...j-1]=={p[0:j-2], p[j-2], ..., p[j-2]},f[i][j]= (s[i-1]==p[j-2] | | p[j-2]== '. ') & F[i-1][j]
Public BooleanIsMatch (String s, String p) {intm =s.length (); intn =p.length (); Boolean[] f =New Boolean[M+1] [N+1]; f[0][0] =true; for(inti = 0; I <= m; i++) { for(intj = 1; J <= N; J + +) { if(P.charat (j-1)! = ' * ') {F[i][j]= I>0 && f[i-1][j-1] && (S.charat (i-1) ==p.charat (j-1) | | P.charat (j-1) = = '. '); } Else{F[i][j]= (J>1&&f[i][j-2]) | | (i>0&& (S.charat (i-1) ==p.charat (j-2) | | P.charat (j-2) = = '. ') &&f[i-1][j]); } } } returnF[m][n]; }
View Code
Leetcode Dynamic Programming Topic Summary "Continuous Update"