leetcode 10 -- Regular Expression Matching

本文深入探讨了如何实现正则表达式的匹配功能,特别关注‘.‘和‘*‘这两个特殊字符的用法。通过递归滑动的方法,作者分享了从无思路到解决问题的心路历程,以及最终实现的代码逻辑。

摘要生成于 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

题意

完成类似正则表达式的匹配功能

思路

针对p[1]是否等于*来进行递归滑动

代码

bool isMatch(char *s,char *p)
{
    if(p[0]=='\0')
    {
        return s[0]=='\0';
    }
    if(s[0]=='\0')
    {
        if(p[1]=='*')
        {
            return isMatch(s,p+2);
        }
        return false;
    }
    if(p[1]=='*')
    {
        if(s[0]==p[0]||p[0]=='.')
        {
            if(strlen(p)>=4 && p[0]==p[2] && p[3]=='*')
                return isMatch(s,p+2);//此处总觉得是有些取巧,针对超时
            return isMatch(s+1,p)||isMatch(s+1,p+2)||isMatch(s,p+2);
        }
        else
        {
            return isMatch(s,p+2);
        }
    }
    else
    {
        if(s[0]==p[0]||p[0]=='.')
        {
            return isMatch(s+1,p+1);
        }
    }
    return false;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值