Leetcode Q10: Regular Expression Matching

题目10:

(该题目拿到手没什么特别好的思路,从网上看的别人的解法,然后写了下自己的理解,需要常回顾)

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
/* 递归算法 */
int isMatch(char* s, char* p) 
{
    if (*p == '\0')
    {
        /* 匹配到最后一个字符,如果s也匹配完则返回true */
        return *s == 0;
    }
    
    /* 后一个元素不为'*',直接对当前元素进行匹配 */
    if (*(p+1) != '*')
    {
        if (*s != 0 && (*s == *p || *p == '.'))
        {
            /* 当前元素匹配到 */
            return (isMatch(s+1, p+1));
        }
        else
        {
            return 0;
        }
    }
    else    /* 后一个元素为'*' */
    {
        /* S: b b b b b a
           P: b * a
           首先探查到s[0]和p[0],p[1]为'*',先判断前面这个元素是否可以匹配,如果不匹配的话,直接将p[0]和p[1]跳过,将s[0...]和p[2...]进行匹配
           如果前面这个元素可以匹配的话,s向后找和s[0]相同的元素,然后去除,和p[2...]匹配,
           例子中将bbbba、bbba、bba、ba、a和,a匹配,如果有可以匹配的,则整个s和p可以匹配。
        */
        while (*s != 0 && (*s == *p || *p == '.'))
        {
            if (isMatch(s, p+2))
            {
                return 1;
            }
            s++;
        }
        /* 第一个元素不同,直接将p[0]和p[1]跳过 */
        return isMatch(s, p+2);
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值