Leetcode 44. Wildcard Matching & Regular Expression Matching (python)

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值