boolisMatch(strings,stringregex){if(s.empty()&®ex.empty())returnfalse;intr_i=0;for(inti=0;i<s.size();++i){if(s[i]==regex[r_i]){returnisMatch(s.substr(i),regex.substr(r_i));}if(regex[r_i]=='*'){// should be regex[r_i+1] == '*'returnisMatch(s.substr(i+1),regex.substr(r_i-1))||isMatch(s.substr(i),regex.substr(r_i+1));}if(regex[r_i]=='.'){returnisMatch(s.substr(i+1),regex.substr(r_i+1));}returnfalse;}returnfalse;}
丑2:
1234567891011121314151617
boolisMatch(strings,stringp){returnimp(s.data(),p.data());}boolimp(constchar*c,constchar*p){if(*c=='\0'&&*p=='\0'){returntrue;}if(*p=='\0'||*c=='\0')returnfalse;// ??? patchingif(*(p+1)=='*'){returnisMatch(c+1,p)||isMatch(c+1,p+2);// should be || isMatch(c, p+2)}if(*c==*p||*p=='.'){// '\0' and '.'returnisMatch(c+1,p+1);}returnfalse;}
正确姿势
DFS
算法清晰的情况下,DFS 解法基本等同于直接翻译:
1234567891011121314151617181920
boolisMatch(strings,stringp){returnimp(s.data(),p.data());}boolimp(constchar*c,constchar*p){// only when regex reaches the end, *c check make senseif(*p=='\0')return*c=='\0';if(*(p+1)=='*'){returnimp(c,p+2)// test if c is end of string then we can safely// recursively call imp(c+1, p)||((*p==*c||(*c!='\0'&&*p=='.'))&&imp(c+1,p));}if(*c==*p||(*c!='\0'&&*p=='.')){returnimp(c+1,p+1);}returnfalse;}
// Copy from LeetcodeboolisMatch(strings,stringp){/** * f[i][j]: if s[0..i-1] matches p[0..j-1] * if p[j - 1] != '*' * f[i][j] = f[i - 1][j - 1] && s[i - 1] == p[j - 1] * if p[j - 1] == '*', denote p[j - 2] with x * f[i][j] is true iff any of the following is true * 1) "x*" repeats 0 time and matches empty: f[i][j - 2] * 2) "x*" repeats >= 1 times and matches "x*x": s[i - 1] == x && f[i - 1][j] * '.' matches any single character */intm=s.size(),n=p.size();vector<vector<bool>>f(m+1,vector<bool>(n+1,false));f[0][0]=true;for(inti=1;i<=m;i++)f[i][0]=false;// p[0.., j - 3, j - 2, j - 1] matches empty iff p[j - 1] is '*' // and p[0..j - 3] matches emptyfor(intj=1;j<=n;j++)f[0][j]=j>1&&'*'==p[j-1]&&f[0][j-2];for(inti=1;i<=m;i++)for(intj=1;j<=n;j++)if(p[j-1]!='*'){f[i][j]=f[i-1][j-1]&&(s[i-1]==p[j-1]||'.'==p[j-1]);}else// p[0] cannot be '*' so no need to check "j > 1" heref[i][j]=f[i][j-2]||(s[i-1]==p[j-2]||'.'==p[j-2])&&f[i-1][j];returnf[m][n];}