[DP] LeetCode Regular Expression Matching

algorithm procedure

  1. if the current text character is matching with the pattern character, which means the last character matched, then the result depends on the previous status: res(r,c)=res(r1,c1)
  2. if the current text character is not matching with the pattern character, then result must be false
  3. if the pattern character is *, then:

    • if the pattern character before the current one is not matching with the current text character, which means the current character has 0 occurrence in the * pattern, then res(r,c)=res(r,c2)
    • if the character before the current pattern character is matching with the text character, which means the text character has one or more occurrence, then res(r,c)=res(r1,c)
    • so the result is:
      res(r,c)=res(r,c2)||(res(r1,c)(ifcharmatches)

example table

text = "aa", pattern = ".*", output = true

0.*
0TF
aFT
aFF

text = "aab", pattern = "c*a*b", output = true

0c*a*b
0TFTFT
aFFFTT
aFFFFT
bFFFFF

code

class Solution {
private:
    bool charMatch(char s, char p) {
        return (s == p) || (p == '.');
    }
public:
    bool isMatch(string s, string p) {
    int R = s.length() + 1, C = p.length() + 1;
        vector<vector<bool>> res(R, vector<bool>(C, false));

        res[0][0] = true;
        for (int c = 1; c < C; ++c) {
            if (p[c-1] == '*') {
                res[0][c] = res[0][c-2];
            }
        }

        for (int r = 1; r < R; ++r) {
            for (int c = 1; c < C; ++c) {
                if (charMatch(s[r-1], p[c-1])) {
                    res[r][c] = res[r-1][c-1];
                } else if (p[c-1] == '*') {
                    res[r][c] = res[r][c-2];
                    if (charMatch(s[r-1], p[c-2])) {
                    res[r][c] = res[r][c] || res[r-1][c];
                    }
                } else {
                    res[r][c] = false;
                }
            }
        }

        return res[s.length()][p.length()];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值