(算法分析Week9)Regular Expression Matching[Hard]

10.Regular Expression Matching[Hard]

题目来源

Description

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

Solution

动态规划Tag里的题目,但是我第一反应是用递归做,所以就试了试递归,居然能AC。
递归:
分情况讨论,p为空直接返回。
p为1就比较第一个,可以相等可以为‘.’。

由于’*’匹配一个或多个在它之前的字符,若p的第二个字符为’*’,s不为空且第一个字符匹配,调用递归函数匹配s和去掉前两个字符的p,若匹配返回true,否则s去掉首字母(已经匹配好的)再和pattern比较。

若不为’*’,就都去掉第一个字符然后递归。

动态规划:

自己是没想出什么好方法,看到discuss有一个说的不错,直接搬运。
Easy DP Java Solution with detailed Explanation

Complexity analysis

O(M*N)
M = s.length()
N = p.length()

Code

(1)递归
class Solution {
public:
    bool isMatch(string s, string p) {
        if (p.empty()) return s.empty();
        if (p.size() == 1) {
            return (s.size() == 1 && (s[0] == p[0] || p[0] == '.'));
        }
        if (p[1] != '*') {
            if (s.empty()) return false;
            return (s[0] == p[0] || p[0] == '.') && isMatch(s.substr(1), p.substr(1));
        }
        while (!s.empty() && (s[0] == p[0] || p[0] == '.')) {
            if (isMatch(s, p.substr(2))) return true;
            s = s.substr(1);
        }
        return isMatch(s, p.substr(2));
    }
};
(2)动态规划
class Solution {
public:
    bool isMatch(string s, string p) {
        int M = s.length(), N = p.length(); 
        vector<vector<bool> > dp(M + 1, vector<bool> (N + 1, false));
        dp[0][0] = true;
        for (int i = 0; i <= M; i++)
            for (int j = 1; j <= N; j++)
                if (p[j - 1] == '*')
                    dp[i][j] = dp[i][j - 2] || (i > 0 && (s[i - 1] == p[j - 2] || p[j - 2] == '.') && dp[i - 1][j]);
                else dp[i][j] = i > 0 && dp[i - 1][j - 1] && (s[i - 1] == p[j - 1] || p[j - 1] == '.');
        return dp[M][N];
    }
};

Result

这里写图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值