[leetcode] 10 Regular Expression Matching

本文详细解析了一种实现正则表达式匹配的算法,包括对特殊字符'.'和'*'的支持。通过递归的方式处理各种情况,如匹配单个字符、零个或多个前导元素等,并给出了具体实现代码及案例分析。

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
这道题最麻烦的大概是理解题意,期初对于最后一个case百思不得其解,导致对于题目无从下手,后来查了Discuss,发现最早的问题就是关于这个case(稍微能够蠢蠢地自我安慰下了)。*并不是之后添加的意思,而是相当于对前面的字符进行说明,例如:

c*==(0个c---无限多个c)       != (1个c---无限多个c);

在明白了这这点之后思路就比较清晰了;

首先:判断是不是两个均结束,倘若一方结束而另一方不是,return false;

之后:判断p下一位是否为*

不为*, 判断两位是否相同,或者*p为‘.’,且s此时不结束;如果相同进入下一位

为*,判断是否相同,相同则s++,当相同的位结束,p+2

不同,则直接p+2,即C*代表0个C的状态


这样的思路可以解决巨大多数的问题,除了(aaa,a*a),因此需要增加处理,即优先判断(s, p+2)是否匹配,如果匹配就return true;

class Solution {
public:
    bool isMatch(const char *s, const char *p) {
    
        if (*p == '\0') return *s == '\0';

        if (*(p+1) != '*') {

            return ((*p == *s) || (*p == '.' && *s != '\0')) && isMatch(s+1, p+1);
        }
	
        while ((*p == *s) || (*p == '.' && *s != '\0')) {
            if (isMatch(s++, p+2)) return true;
        }
        return isMatch(s, p+2);
    }
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值