欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode44 Wildcard Matching

发布时间:2024/8/26 编程问答 60 豆豆
生活随笔 收集整理的这篇文章主要介绍了 LeetCode44 Wildcard Matching 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

题目:

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 };

 

转载于:https://www.cnblogs.com/wangxiaobao/p/5847358.html

总结

以上是生活随笔为你收集整理的LeetCode44 Wildcard Matching的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。