10. Regular Expression Matching (dp)

Implement regular expression matching with support for '.' and '*'.

'.' Matches any single character.
'*' Matches zero or more of the preceding element.

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", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true
这个跟之前多校有道题很像,除了"."的匹配不一样。
#include <iostream>
#include <algorithm>
#include <string.h>
#include <vector>
#include <sstream>
#include <stdio.h>
using namespace std;
bool isMatch(const string& s, const string& p) {
    int slen = s.size();
    int plen = p.size();
    //dp[i + 1][j + 1]表示 s[i]跟p[j]当前的匹配情况
    /**
     * bp[i + 1][j + 1]: if s[0..i] matches p[0..j]
     * if p[j] != '*'
     * bp[i + 1][j + 1] = bp[i][j] && s[i] == p[j]
     * if p[j] == '*', denote p[j - 1] with x,
     * then bp[i + 1][j + 1] is true iff any of the following is true
     * 1) "x*" repeats 0 time and matches empty: bp[i + 1][j -1]
     * 2) "x*" repeats 1 time and matches x: bp[i + 1][j]
     * 3) "x*" repeats >= 2 times and matches "x*x": s[i] == x && bp[i][j + 1]
     * '.' matches any single character
     可以画一个方格图,就像最长公共子序列一样,就比较好理解了
     */
    
    bool dp[slen + 1][plen + 1];
    dp[0][0] = 1;
    for (int i = 0; i < slen; ++i) {
        dp[i + 1][0] = 0;
    }
    for (int i = 0; i < plen; ++i) {
        dp[0][i + 1] = i > 0 && p[i] == '*' && dp[0][i - 1];
    }
    
    for (int i = 0; i < slen; ++i) {
        for (int j = 0; j < plen; ++j) {
            if (p[j] == '*') {           //x*匹配0个x的时候         x*匹配1个x的时候   x*匹配>=2个x的时候 x*x
                dp[i + 1][j + 1] = (j > 0 && dp[i + 1][j - 1]) || dp[i + 1][j] || (dp[i][j + 1] && j > 0 && (p[j - 1] == '.' || s[i] == p[j - 1]));
            } else {
                dp[i + 1][j + 1] = dp[i][j] && (s[i] == p[j] || p[j] == '.');
            }
        }
    }
    
    return dp[slen][plen];
}
int main() {
    cout << isMatch("aab", "c*a*b") << endl;;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值