问题
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)
例子
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
分析
参考10. Regular Expression Matching,其中'?'就相当于Regular Expression Matching中的'.'。'*'变成了任意字符串,包括空串。
同样可以使用动态规划:
状态表
dp[i][j],表示s[0, i - 1]和p[0, j - 1]是否匹配初始状态
dp[0][0] = true s为空,p为空,必然匹配;
dp[i][0] = false, i >= 1 s非空,p为空,必然不匹配;
dp[0][j] = p[j - 1] == '*' && dp[0][j - 1], j >= 1 s为空,只有当p[j - 1]为'*'并且dp[0][j - 1]为true时才能匹配。状态转移方程
dp[i][j] = dp[i - 1][j - 1] && (s[i - 1] == p[j - 1] || p[j - 1] == '?'); if p[j - 1] != '*'
dp[i][j] = dp[i][j - 1] || dp[i - 1][j]; if p[j - 1] == '*' dp[i][j] = dp[i][j - 1]表示'*'被解释为空串;dp[i][j] = dp[i - 1][j]表示'*'被解释成的字符串的末尾是s[i - 1].
要点
dp
时间复杂度
O(nm)
空间复杂度
O(nm)
代码
class Solution {
public:
bool isMatch(string s, string p) {
int m = s.size(), n = p.size();
vector<vector<bool>> dp(m + 1, vector<bool>(n + 1, false));
dp[0][0] = true;
for (int i = 1; i <= m; i++)
dp[i][0] = false;
for (int j = 1; j <= n; j++)
dp[0][j] = dp[0][j - 1] && p[j - 1] == '*';
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
if (p[j - 1] != '*')
dp[i][j] = dp[i - 1][j - 1] && (s[i - 1] == p[j - 1] || p[j - 1] == '?');
else
dp[i][j] = dp[i][j - 1] || dp[i - 1][j];
return dp[m][n];
}
};