leetcode 44: Wildcard Matching

96 篇文章 0 订阅
68 篇文章 0 订阅

Implement wildcard pattern matching with support for '?' and '*'.

'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
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", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false
递归超时,通不过. 
注意: 第12行中,循环时,实参  p的值一直没变,s的值一直在加加 -----所以迭代版本中 要保存p的值,++s的值!!!--对应迭代版本中的 25 26 行
(是为了 p中以 ‘ * ’ 后某个位置为起点,s中某个位置为起点 判断匹配失败后 再回到某次++s的位置,从‘ * ’ 后第一位置从头再来---跳过了一些注定无法匹配的起始点 )
bool isMatch(const char *s, const char *p) 
{
    if (s == NULL || p == NULL) return false;
    if (*p == '\0') return *s == '\0';
    
    if (*p == '*')
    {
        while (*p == '*') ++p;
        if(*p=='\0')
            return true;
        while (*s != '\0')
        {
            if (isMatch(s, p)) return true; //这里 p的值一直没变,s的值一直在加加-----所以迭代版本中 要保存p的值,++s的值!!!
            ++s;
        }
        
        return isMatch(s, p);
    }
    else if ((*s != '\0' && *p == '?') || *p == *s)
    {
        return isMatch(s + 1, p + 1);
    }
    
    return false;
}
迭代版本要注意: 找到*的时候,s不要++ 跳过
bool isMatch(const char *s, const char *p) 
{
    if (s == NULL || p == NULL) return false;
    if (*p == '\0') return *s == '\0';
    char *backS=NULL;
    char *backP=NULL;
    while(*s)  //循环中s永远不会是结束0,如果p是结束0 那会进行 (3)、(4)判断
    {
        if (*p == '*') // (1)
        {
            while (*p == '*') ++p;
            if(*p=='\0')
                return true;
            backS=s;// s当前位置
            backP=p;// * 后面第一个位置
            // s++;不能s++,如果s++ 那就跳过s中当前字符了,同时也跳过了p中*,只要跳过* 就可以 ,* 当不存在直接跳过,s中当前字符匹配*后第一个
        }
        else if ( *p == '?' || *p == *s) //(2)
        {
            s++;
            p++;
        }
        else if(backS) //(3)
        {
            s=++backS;
            p=backP;
        }
        else // (4) 一种是 从来就没有* ,没有backS ; 一种是 ++backs 导致backs==0 到末尾了
            return false;
    }
    while(*p=='*')
        p++;
    return (*p=='\0' && *s=='\0');
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值