Description:
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).
Note:
采用动态规划。开启(M+1)*(N+1)的数组空间。dp[0][i],dp[i][0]为其中一个字符串不包含任何字符的情况。
p[i-1]=='*'(注意字符串的index和dp中的index差1),找到一个最小j使得dp[i-1][j]为true,设置dp[i][j~N]均为true。
p[i-1]!='*',若dp[i-1][j-1]为true且p[i-1]=='?'或p[i-1]==s[j-1]的情况下,设置dp[i][j]=true。
最终dp[M][N]即为两个字符串是否match的结果。
Code:
class Solution {
public:
/**
* @param s: A string
* @param p: A string includes "?" and "*"
* @return: A boolean
*/
bool isMatch(string &s, string &p) {
// write your code here
int sl = s.size();
int pl = p.size();
bool** dp = new bool*[pl + 1];
for (int i = 0; i<pl + 1; i++) {
dp[i] = new bool[sl + 1];
for (int j = 0; j < sl + 1; j++)
dp[i][j] = 0;
}
int j;
dp[0][0] = 1;
for (int i = 1; i<pl + 1; i++) {
if (p[i - 1] == '*') {
j = 0;
while (!dp[i - 1][j] && j<sl + 1) {
j++;
}
for (int k = j; k<sl + 1; k++)
dp[i][k] = 1;
}
else {
for (int k = 1; k<sl + 1; k++) {
if (dp[i - 1][k - 1]) {
if (p[i - 1] == '?' || p[i - 1] == s[k - 1])
dp[i][k] = 1;
}
}
}
}
bool result = dp[pl][sl];
for (int i = 0; i<pl + 1; i++)
delete[] dp[i];
delete[] dp;
return result;
}
};