LeetCode: 44. Wildcard Matching
来源:互联网 发布:u盘启动ubuntu系统 编辑:程序博客网 时间:2024/06/07 05:43
LeetCode: 44. 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
题目大意: 给定模式串 p, 匹配串 s。其中,p含有通配符 (Wildcard)。 ‘?’ 代表可以匹配任意一个字符, ‘*’ 代表可以匹配任意个数任意字符。 判断 p 串 和 s 串是否匹配。
解题思路 — 动态规划
- 记s串的前i个字符和p串的前j个字符能否匹配为
dp[i][j]
。 - 如果模式串p和匹配串s都为空,则匹配成功,
dp[0][0] = true;
。 - 如果模式串p为空,s串不为空, 则匹配失败,
dp[i][0] = false
, 其中0 < i <= s.size()
。 如果模式串p不为空, s串为空,i > 0, 若
p[i-1] == '*'
则dp[0][i]
的真值受dp[0][i-1] 的影响。
否则,dp[0][i] = false
。即,当p串和s串都不为空时, 状态转移方程如下,
AC代码
class Solution {public: bool isMatch(string s, string p) { vector<vector<bool>> dp; dp.resize(s.size()+1); for(auto& vb : dp) vb.resize(p.size()+1, false); dp[0][0] = true; for(int i = 1; i <= p.size(); ++i) { if(p[i-1] == '*') dp[0][i] = dp[0][i-1]; } for(int i = 1; i <= s.size(); ++i) { for(int j = 1; j <= p.size(); ++j) { if(s[i-1] == p[j-1] || p[j-1] == '?') { dp[i][j] = dp[i-1][j-1]; } else if(p[j-1] == '*') { for(int k = 0; k <= i; ++k) { if(dp[k][j-1] == true) { dp[i][j] = true; break; } } } else { dp[i][j] = false; } } } return dp[s.size()][p.size()]; }};
- 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
- LeetCode 44. Wildcard Matching
- 44. Wildcard Matching -- LeetCode
- LeetCode 44. Wildcard Matching
- 多态
- Android优雅之路——findViewBy Button
- 【深度学习】深度学习简介
- 自动装箱
- 紫书章五例二 木块问题 UVA 101(vector)
- LeetCode: 44. Wildcard Matching
- c++基础之继承
- Android 的ProgressDialog的dismiss()与cancel()方法的区别
- Java 创建文件输出流的时候报错
- 巧力避免ViewPager的预加载数据,Tablayout+Fragment+viewPager
- Android Studio安装插件
- Opendaylight Boron-SR2 安装
- 关于java.time
- 关于我在开发websocket遇到的问题以及一些解答