题目:
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
分析:
跟第10题Regular Expression Matching很像,从正则表达式匹配变成了通配符匹配,用动态规划的方法做的话, 比之前这个题要来的简单。
还是双序列动态规划,用dp[i][j]表示s前i个与p前j个是否能匹配。
分p[j - 1]的几种情况,
当 (p[j - 1] == s[i - i] 或者 p[j - 1] == '?')且 dp[i - 1][j - 1] == true, 则 dp[i][j] == true;
当 p[j - 1] == '*'时, (dp[i - 1][j] == true|| dp[i][j - 1] == true), 则 dp[i][j] == true;
初始化第一行,第一列即可。
注意: 动归的算法在leetcode上有两组样例应该是过不了的,可能还有贪心的思路可以优化,但动归的思路应该更值得学习(更有通用性),回头有时间再来补上贪心的思路。
如果要通过样例的话,可以有个小作弊,就是当s.size() > 3000时,返回false,处理掉那两个大样例。
代码:
1 class Solution { 2 public: 3 bool isMatch(string s, string p) { 4 if (p.size() > 3000 || s.size() > 3000) { 5 return false; 6 } 7 bool dp[s.size() + 1][p.size() + 1] = {false}; 8 dp[0][0] = true; 9 for (int i = 1; i <= p.size(); ++i) { 10 dp[0][i] = dp[0][i - 1] && (p[i - 1] == '*'); 11 } 12 for (int i = 1; i <= s.size(); ++i) { 13 for (int j = 1; j <= p.size(); ++j) { 14 if ((p[j - 1] == s[i - 1] || p[j - 1] == '?') && dp[i - 1][j - 1] == true) { 15 dp[i][j] = true; 16 } 17 if (p[j - 1] == '*' && (dp[i - 1][j] || dp[i][j - 1]) ){ 18 dp[i][j] = true; 19 } 20 } 21 } 22 return dp[s.size()][p.size()]; 23 } 24 };