Wildcard Matching -- leetcode

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


此算法在leetcode上实际执行时间为 27ms。


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

        while (*p == '*') ++p;

        return !*p;
    }
};


主要是对’*’的处理。

1.遇到’*’,首先偿试匹配0个。即不消耗当前s的字符。用p后续的匹配串,去对s进行匹配。

2.如果失败,则消耗掉当前s的字符。

此题用递归写的法,比较容易,但是在时间上很难被AC。原因在于递归时回溯的比较多。

 

此题想要在时间上被AC,要利用一个优化条件:

如果匹配失败,则只用回退最近上一个*处继续进行第2步处理。

 

参考:

https://oj.leetcode.com/discuss/10133/linear-runtime-and-constant-space-solution

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值