原题:
mplement wildcard pattern matching with support for
解决方法:
代码:
mplement 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
解决方法:
可以使用DP来解这道题,dp[i][j]表示s中的i个字符是否跟p中的j个字符匹配。
- 注意数组的初始化,首先0跟0个字符匹配。其次p开头的'*'都匹配。
- 当p[j]不是'*'时,则i-1和j-1匹配的前途下,要么p[j]=='?',要么s[i]==p[j],即dp[i+1][j+1] = dp[i][j] && (p[j]=='?' || s[i]= p[j]);
- 当p[j] =='*'时,可以不匹配任何字符dp[i+1][j],也可以匹配字符dp[i][j+1]。即dp[i+1][j+1] = dp[i][j+1] || dp[i+1][j]。
代码:
bool isMatch(string s, string p) {
int n = s.size(), m = p.size();
vector<vector<bool>> dp(n+1, vector<bool>(m+1, 0));
dp[0][0] = true;
for(int j = 0; j < m; j++){
if (p[j] != '*')
break;
dp[0][j+1] = true;
}
for(int i = 0 ; i < n;i++){
for(int j = 0; j < m; j++){
if (p[j] == '*'){
dp[i+1][j+1] = dp[i+1][j] || dp[i][j+1];
}else{
dp[i+1][j+1] = dp[i][j] && ( s[i]==p[j] || p[j] == '?' );
}
}
}
return dp[n][m];
}