LeetCode44 Wildcard Matching
2016-09-06 22:04
281 查看
题目:
Implement wildcard pattern matching with support for
分析:
跟第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,处理掉那两个大样例。
代码:
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,处理掉那两个大样例。
代码:
class Solution { public: bool isMatch(string s, string p) { if (p.size() > 3000 || s.size() > 3000) { return false; } bool dp[s.size() + 1][p.size() + 1] = {false}; dp[0][0] = true; for (int i = 1; i <= p.size(); ++i) { dp[0][i] = dp[0][i - 1] && (p[i - 1] == '*'); } for (int i = 1; i <= s.size(); ++i) { for (int j = 1; j <= p.size(); ++j) { if ((p[j - 1] == s[i - 1] || p[j - 1] == '?') && dp[i - 1][j - 1] == true) { dp[i][j] = true; } if (p[j - 1] == '*' && (dp[i - 1][j] || dp[i][j - 1]) ){ dp[i][j] = true; } } } return dp[s.size()][p.size()]; } };
相关文章推荐
- LeetCode --- 44. Wildcard Matching
- Leetcode:44. Wildcard Matching
- leetcode 44. Wildcard Matching
- leetcode 44. Wildcard Matching
- leetcode 10 Regular Expression Matching & 44 Wildcard Matching
- Leetcode习题解答:44. Wildcard Matching
- leetcode[44]Wildcard Matching
- [leetcode 44] Wildcard Matching
- leetcode 44. Wildcard Matching
- LeetCode 44:Wildcard Matching
- LeetCode 44. Wildcard Matching
- leetcode 44. Wildcard Matching
- [leetcode[ 【字符串】 44. Wildcard Matching
- Leetcode 44. Wildcard Matching
- leetcode 44. Wildcard Matching
- LeetCode - 44. Wildcard Matching
- Leetcode 44. Wildcard Matching
- [LeetCode]--44. Wildcard Matching
- leetcode(44) - Wildcard Matching
- LeetCode 44. Wildcard Matching