LeetCode(44) Wildcard Matching

题目如下:

'?' 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


分析如下:

确实是难题了。最难处理的是*的问题。haoel大牛的代码写得简洁易懂,所以这道题目就抄他的了。

因为p中的*可以匹配s中的0个或一个或多个,到底匹配几个呢?这取决于*的下一位。

比如看 s = abbb;      p = a*b 这个例子。s0 = p0= a, p1=*, 那么*到底匹配几个b呢?看*后的p2 = b, 因为p2如果和s3=b匹配了,那么可以用*去匹配s1~s2,即bb,这样就完成了匹配。如果*匹配s的方式为其它方式,那么都没法得出s和p匹配。

这说明,这道题目的关键就是在遇到p中的*之后,检验每一种可p中的*和s中的字符的匹配方式。

为了实现这一点,在出现*时,需要保留此时的*的位置和s中的对应位置。

可以对照代码看看下面几个例子,体会*的用途。

 s = "aab"        p = "a*a*b"; // true
 s = "abbb";      p = "a*b"; //true
 s = "abb";       p = "a*bb";//true
 s = "abddbbb";   p = "a*d*b";//true
 s = "abdb";      p = "a**";//true
 s = "a";         p = "a**";//true

最后,除了*这一个难点之外,题目中的edge case也不少,可以看代码体会。


我的代码:

100% derived from haoel 

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值