-
-
Save saswata-dutta/e9c3b32573748161c51874fbf1d42882 to your computer and use it in GitHub Desktop.
Match a regular expression (including '.' and '*' using dynamic programming
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bool canMatch(char a, char b) | |
{ | |
return (a == b || b == '.'); | |
} | |
bool isMatch(const char *s, const char *p) { | |
int lS = strlen(s); | |
int lP = strlen(p); | |
vector<vector<bool> > F(lS + 1, vector<bool>(lP + 1)); | |
F[0][0] = true; | |
for (int i = 0; i <= lS; i++) | |
{ | |
for (int j = 1; j <= lP; j++) | |
{ | |
if(i>0) | |
// matches one character, index of both string and pattern move forward by 1 | |
if (F[i-1][j-1] && canMatch(s[i-1], p[j-1])) | |
{ | |
F[i][j] = true; | |
continue; | |
} | |
if (i > 0 && j > 1) | |
// matches the situation when the next char in the string is the same as the char before the '*' in the pattern | |
// pre-match: string xxxCyyy, pattern mmmC*nnn, xxx matches mmmC* | |
// current match: xxxC matches mmmC* | |
if (F[i-1][j] && canMatch(s[i-1], p[j-2]) && p[j-1] == '*') | |
{ | |
F[i][j] = true; | |
continue; | |
} | |
if (j > 1) | |
// matches the situation when the next two chars in the pattern is in the form of C* | |
// pre-match: string xxxyyy, pattern mmmC*nnn, xxx matches mmm | |
// current match: xxx matches mmmC* | |
if (F[i][j-2] && p[j-1] == '*') | |
{ | |
F[i][j] = true; | |
continue; | |
} | |
} | |
} | |
return F[lS][lP]; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment