Wildcard Matching

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

 

思路:

先是递归,不能过大集合;

循环可以过,但是p == '*'的情况需要特殊处理,用两个指针记录p == '*'时的s和p的位置。

因为p的*可以代表很多字符,需要确定*代表s中的那些字符

 

代码:

递归版

class Solution {
public:
    bool isMatch(const char *s, const char *p) {
        if (*p == '*')
        {
            while (*p == '*')   p++;
            if (*p == '\0') return true;
            while (*s != '\0' && !isMatch(s, p))
                s++;
            return *s != '\0';
        }
        else if (*p == '\0' || *s == '\0')
            return *p == *s;
        else if (*p == '?' || *p == *s)
            return isMatch(++s, ++p);
        else return false;
    }
};


 循环版

class Solution {
public:
    bool isMatch(const char *s, const char *p)
    {
        if (!s && !p)
            return true;

        const char *ss = NULL;
        const char *sp = NULL;

        while (*s)
        {
            if (*s == *p || *p == '?')
            {
                s++;
                p++;
            }
            else if (*p == '*')
            {
                while (*p == '*')
                    p++;
                if (*p == '\0')
                    return true;
                ss = s;
                sp = p;
            }
            else if ((*p == '\0' || *p != *s) && sp)
            {
                s = ++ss;
                p = sp;
            }
            else return false;
        }
        while (*p)
            if (*p++ != '*')
                return false;
        return true;
    }
};
posted on 2013-08-11 09:05  赵乐ACM 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/dollarzhaole/p/3250983.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值