Implement wildcard pattern matching with support for '?'
and '*'
.
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false
bool match(char a, char b) {
return a == b || b == '?';
}
bool isMatch(string target, string pattern) {
int m = target.size();
int n = pattern.size();
vector< vector<bool> > dp(m + 1, vector<bool>(n + 1));
dp[0][0] = true;
for(int i = 0; i <= m; ++i) {
for(int j = 0; j <= n; ++j) {
if(!i && !j) continue;
if(i > 0 && j > 0) {
if(match(target[i-1], pattern[j-1]) && dp[i-1][j-1]) // regular match
dp[i][j]= true;
}
if(i > 0 && j > 0) { //cover three, * matches 0(i, j - 1), * matches more than 1(i, j - 1), * matches 1, (i-1, j - 1)
if(pattern[j-1] == '*' && (dp[i-1][j] || dp[i][j-1] || dp[i-1][j-1])) dp[i][j] = true;
}
if(j > 0) { // cover one case. aaa, aaa* --> * matches 0.
if(pattern[j-1] == '*' && dp[i][j-1]) dp[i][j] = true;
}
}
}
return dp[m][n];
}