This problem and the previous regular Expression matching a bit similar, the first reaction is the same as before, with the return to do
BOOLDomatch (Char*s,Char*p) { if(*p = =' /')return*s = =' /'; if(*p = ='*') { while(*s!=' /')//wildcard matches 0 times, 1 times · { if(Domatch (s,p+1)) return true; S++; } //wildcard matches are still not matched after matching returnDomatch (s,p+1); } Else { //if (*p!=*s && *p!= '. ') return false; //return Domatch (s+1,p+1); if(*p = = *s | | (*p = ='?'&& *s! =' /')) returnDomatch (s+1, p+1); return false; }}BOOLIsMatch (Char* S,Char*p) {if(*p==' /')return*s==' /'; Char*new_p = (Char*)malloc(strlen (p)); intj=0; //the first preprocessing of P, multiple * becomes a for(intI=0; I<strlen (p); i++) { if(i>0&& p[i]=='*'&& p[i-1]=='*') Continue; NEW_P[J]=P[i]; J++; } New_p[j]=' /'; returnDomatch (s,new_p);}
Timed out ... This is due to the fact that there is a repeat comparison. For example, when p = "C*ab*c", s = "Cddabbac", when encountering the first *, the remainder of P's "ab*c" and the remainder of S "Ddabbac" need to be processed recursively. When you encounter a second *, you need to compare the remainder, so you need to use dynamic planning to eliminate duplicate sub-problems.
Dp[i][j] represents to P[i-1] and s[j-1] so far, so the current character is * when dp[i][j]=dp[i-1][j]| | dp[i][j-1]| | DP[I-1][J-1]
The current character is in other cases dp[i]pj]=dp[i-1][j-1] && (p[i-1]== '? ' | | p[i-1]==s[j-1])
Here in order to facilitate the establishment of the initial value, add a row, and make dp[0][0]=true;
We notice that the DP value is only related to the previous row and the previous column, so you can reduce the array to two rows to save space.
classSolution { Public: BOOLIsMatch (stringSstringp) {intS_len =s.length (); intP_len =p.length (); Vector<vector<BOOL>>DP (2,vector<BOOL> (s_len+1,false)); dp[0][0] =1; for(intI=1; i<=p_len;i++) { intcur=i%2; intprev= (i+1)%2; dp[cur][0]=dp[prev][0]&&p[i-1]=='*'; for(intj=1; j<=s_len;j++) { if(p[i-1]=='*') Dp[cur][j]= dp[cur][j-1] || DP[PREV][J] | | dp[prev][j-1]; ElseDp[cur][j]= dp[prev][j-1] && (p[i-1]=='?'|| p[i-1]==s[j-1]); } } returndp[p_len%2][s_len]; }};
Leetcode-44. Wildcard Matching