leetcode #44 in cpp
来源:互联网 发布:面板数据到底是怎样的 编辑:程序博客网 时间:2024/06/05 18:54
Solution:
We use DP to solve this problem.
Initialize bool dp[pattern length + 1][ s length + 1] = {false}, where dp[i][j] = true if pattern[0....i-1] matches s[0....j-1] and false otherwise.
The reason we use pattern length + 1 and s length + 1is that during iteration we would always determine d[i][j] by d[i-1][j-1] or d[i][j-1] or d[i-1][j]. If we start i,j from 0 then i-1 and j-1 would be out of bound. It is convenient to have one more row and one more column, with dp[0][j] means if the head of pattern ""(empty string) matches s[0...j-1] and dp[i][0] means if the head of string ""(empty string) matches pattern[0....i-1] .For example, compare pattern = "abcd", s = "ab*c"
Next we find how to get dp[i][j] from other entries.
Suppose we are now to get dp[i][j]. It should be related to what p[i-1] and s[j-1] is.
string:
s[0............j-2]s[j-1]pattern:
p[0.............i-2]p[i-1]There are three cases:
1. p[i-1] == '*':
In this case, pattern[0....i-1] matches s[0....j-1] if:
1.1 p[0.....i-2] matches s[0....j-1]. (since p[i-1] can match an empty string)
1.2. p[0....i-2] matches s[0....j-2]. (since p[i-1] can match any character or string and thus it matches s[j-1])
dp[i][j] = dp[i-1][j] || dp[i-1][j-1]
2. p[i-1] == '?': Note that '?' could not match an empty string. It can just match one character
In this case, pattern[0....i-1] matches s[0....j-1] if:
2.1 p[0....i-2] matches s[0....j-2]. (since p[i-1] matches s[j-1] since '?' could match any character)
dp[i][j] = dp[i-1][j-1];
3. p[i-1] != '?' and p[i-1] != '*':
In this case, pattern[0....i-1] matches s[0....j-1] if:
class Solution {public: bool isMatch(string s, string p) { vector<vector<bool>> dp(p.length()+1,vector<bool>(s.length()+1)); dp[0][0] = true; for(int i = 1; i < p.length()+1; i ++) if(p[i-1] == '*'){ dp[i][0] = dp[i-1][0]; } for(int i = 1; i < p.length()+1; i ++){ for(int j = 1; j < s.length()+1; j ++){ if(p[i-1] == '?' || p[i-1] == s[j-1]){ dp[i][j] = dp[i-1][j-1]; }else if(p[i-1] == '*' &&(dp[i-1][j-1]||dp[i-1][j]||dp[i][j-1])) dp[i][j] = true; } } return dp[p.length()][s.length()]; }};
- leetcode #44 in cpp
- leetcode #12 in cpp
- Leetcode #13 in cpp
- Leetcode #14 in cpp
- leetcode %15 in cpp
- leetcode #16 in cpp
- leetcode #17 in cpp
- leetcode #18 in cpp
- leetcode #20 in cpp
- leetcode #21 in cpp
- leetcode #22 in cpp
- leetcode #23 in cpp
- leetcode #24 in cpp
- leetcode #25 in cpp
- leetcode #26 in cpp
- leetcode #27 in cpp
- leetcode #28 in cpp
- leetcode #29 in cpp
- Hdu 3552 I can do it!(贪心)
- Spring-EL表达式
- 斯坦福大学机器学习笔记(4)-logistic回归
- 简单分析CVE-2015-1805
- 经典面试题:一张表区别DOM解析和SAX解析XML
- leetcode #44 in cpp
- 二叉树的创建和查找指定值路径
- linux 内核与用户空间通信
- Toast Notification
- 【LeetCode-189】Rotate Array(C++)
- HDU1331 Function Run Fun
- 1006. 换个格式输出整数 (15)
- 【c++程序】链表前插、插入和后插
- C++primer_第九章_顺序容器_学习跟踪