第十四周:[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


分情况用递归解决。
首先便携式一个函数判断s和p当前字符匹配是否匹配:若字符相同或p为’.’,则”s和p当前字符匹配”。
1、若p为空,若s也为空,返回true,反之返回false;
2、若p的长度为1,若s长度也为1,且”s和p当前字符匹配”,则返回true,反之返回false;
3、若p的第二个字符不为’*’,若此时s为空返回false,否则若”s和p当前字符匹配”,再从各自的第二个字符开始调用递归函数匹配;
4、若p的第二个字符为’*’,若”s和p当前字符匹配”,调用递归函数匹配s和去掉前两个字符的p,若匹配返回true,否则s去掉首字母继续上述匹配过程;
5、返回调用递归函数匹配s和去掉前两个字符的p的结果;


bool SMatchP(char s,char p){
    return s == p || p == '.';
}

bool isMatch(string s, string p) {
    if(p.empty())
        return s.empty();
    if(p.size() == 1)
        return (s.size() == 1 && SMatchP(s[0],p[0]));
    if(p[1] != '*'){
        if(s.empty())
            return false;
        return SMatchP(s[0],p[0]) && isMatch(s.substr(1), p.substr(1));
    }
    while (!s.empty() && SMatchP(s[0],p[0])) {
        if(isMatch(s,p.substr(2)))
            return true;
        s = s.substr(1);
    }
    return isMatch(s, p.substr(2));
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值