leetcode_c++: Regular Expression Matching(010)

本文介绍了一种正则表达式匹配算法,支持‘.’和‘*’两种特殊字符,其中‘.’匹配任意单个字符,‘*’匹配其前导元素零次或多次。通过递归方法实现了字符串与正则表达式的完全匹配,并提供了C++代码示例及多种解决方案,包括深度优先搜索(DFS)、动态规划(DP)和使用内置函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

//字符串和正则表达式,是否匹配


算法

DFS
O(n!)


class Solution {
public:
    bool isMatch(string s, string p) {
        if(s.length() == 0){
            if(p.length() & 1) return false;
            else{
                for(int i = 1; i < p.length(); i += 2) if(p[i] != '*') return false;
                return true;
            }
        }
        if(p.length() == 0) return false;
        if(p.length() > 1 && p[1] == '*'){
            if(p[0] == '.' || s[0] == p[0]) return isMatch(s.substr(1), p) || isMatch(s, p.substr(2));
            else return isMatch(s, p.substr(2));
        }
        else{
            if(p[0] == '.' || p[0] == s[0]) return isMatch(s.substr(1), p.substr(1));
            else return false;
        }
    }
};

算法

DF
偷懒的方法是直接用语言自带的正则实现。(Python 又是一句话 =w=)
用 DFS 的方法
可以用 DP 的方法
用数组 DP :dp[i][j] 表示 s[0..i] 和 p[0..j] 是否 match,当 p[j] != ‘‘,b[i + 1][j + 1] = b[i][j] && s[i] == p[j] ,当 p[j] == ‘’ 要再分类讨论,具体可以参考 DP C++,还可以压缩下把 dp 降成一维:参考这里
用记忆化,就是把算过的结果保存下来,下次就不用再算了

https://discuss.leetcode.com/topic/6183/my-concise-recursive-and-dp-solutions-with-full-explanation-in-c

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值