Wins the offer (leetcode 10.) regular expression matching

 

 This problem did a year ago, had just began to brush leetcode, submitted dozens of trouble, that did not put a tube. Today wins the offer encountered this problem, finally did come out, dp used.

. 1  class Solution {
 2  public :
 . 3      BOOL IsMatch ( String S, String P) {
 . 4          int s_len s.size = (), = p_len P.SIZE ();
 . 5          Vector <Vector < BOOL >> DP (+ s_len . 1 , Vector < BOOL > (+ p_len . 1 , to false ));
 . 6          // DP [I] [J] represents the s [0, i-1] and p [0, j-1] can fit 
. 7          DP [ 0 ] [ 0 ] = to true ; // empty string matches the empty string 
. 8          for ( int i=1;i<=p_len;++i){
 9             dp[0][i]=i>1 and p[i-1]=='*' and dp[0][i-2];
10         }
11         for(int i=1;i<=s_len;++i){
12             for(int j=1;j<=p_len;++j){
13                 if(p[j-1]=='*'){
14                     if(p[j-2]!='.'){//数字+'*'
15                         dp[i][j]=dp[i][j-2] or (s[i-1]==p[j-2] and (dp[i-1][j-2] or dp[i-1][j-1]));
16                     }
17                     else{//'.'+'*'
18                         for(int k=i;k>= 0;--k){
19                             if(dp[k][j-2]){
20                                 dp[i][j]=true;
21                                 break;
22                             }
23                         }
24                     }
25                 }
26                 else if(p[j-1]=='.'){
27                     dp[i][j]=dp[i-1][j-1];
28                 }
29                 else{//数字
30                     dp[i][j]=p[j-1]==s[i-1] and dp[i-1][j-1];
31                 }
32             }
33         }
34         return dp.back().back();
35     }
36 };

 

Guess you like

Origin www.cnblogs.com/FdWzy/p/12293663.html