Leetcode 44. Wildcard Matching
解法:动态规划
这道题目在于理解代码中的step2和step4的第一部分
关于step 4的第一步份,实际上可以用0,1背包跟完全背包之前的关系来理解
class Solution {
public:
bool isMatch(string s, string p) {
int sl = s.length();
int pl = p.length();
// step1: dp[i][j]: s[0..i-1] matches p[0..j-1]
bool dp[sl+1][pl+1];
dp[0][0] = true;
// step2:for empty s, all pattern except **...** will be false
for (int i=1;i<pl+1;i++){
dp[0][i] = dp[0][i-1] && p[i-1]=='*';
}
// step3:for empty p, all non empty s will be false
for (int i=1;i<sl+1;i++){
dp[i][0] = false;
}
// step 4
for (int i=1;i<sl+1;i++){
for (int j=1;j<pl+1;j++){
// if p[j-1]=='*', there are three cases: 1. '*' matches an empty string, then dp[i][j]==dp[i][j-1]; 2. '*' matches only the char s[i-1], then dp[i][j] = dp[i-1][j] 3. '*' matches more than one char in s, then it is also dp[i][j] = dp[i-1][j]. Because for dp[i-1][j], the '*' is still at the end of the pattern, and it can continue move forward to dp[i-2][j],dp[i-3][j] until dp[i-n][j] is not True. And dp[i-n][j] will be already computed because it is the subproblem of dp[i-1][j]
if (p[j-1]=='*'){
dp[i][j] = dp[i-1][j] or dp[i][j-1];
// if p[j-1]=='?', then '?' only match the last char of s
// if s[i-1]==p[j-1], then previous s and pattern must match
}else if(p[j-1]=='?' or s[i-1]==p[j-1]){
dp[i][j] = dp[i-1][j-1];
}else{
dp[i][j] = false;
}
}
}
return dp[sl][pl];
}
};
参考:https://leetcode.com/problems/wildcard-matching/discuss/902836/Very-easy-to-understand-DP-solution-with-simple-explanation
Leetcode Regular Expression Matching
待做
参考:https://leetcode.com/problems/regular-expression-matching/discuss/902592/C%2B%2B-100-faster-Solution