算法分析与设计课程(4):【leetcode】Wildcard Matching

Description:

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分成若干部分,然后判断,这几部分是不是可以能在s中匹配到。先定义两个指针从s和p的头出发如果p的第一个部分可以和s的前面部分匹配,那么两个指针往右移同样长度到第二部分,直到找到最后。例如,如果s为“abba”,p为“a*a”。首先,我们判断*前面那部分是不是和s的前面部分匹配。’a‘和‘a‘可以匹配;那么判断p中第二个‘a‘在s中能否匹配。发现可以,所以 返回true。这个的时间复杂度是(O(n))。
代码如下:
class Solution(object):
    def match(self, s, p, i, j, size):
        k = 0
        while k < size:
            if s[k + i] != p[j + k] and p[j + k] != '?':
                return False
            k += 1
        return True

    def isMatch(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: bool
        """
        if s == p or p == "*":
            return True
        size = len(p);
        d = []
        if size == 0 or len(s) == 0:
            return False
        for i in range(size):
            if p[i] == '*':
                d.append(i)
        i = 0;
        j = 0;
        k = 0;
        ss = len(s)
        if len(d) == 0:
            if ss != size:
                return False
            return self.match(s, p, 0, 0, size)
        first = True
        while i < ss:
            if ss - i < size - j - len(d) + k:
                return False
            if self.match(s, p, i, j, d[k] - j):
                first = False
                if k == len(d) - 1:
                    if d[k] == size - 1:
                        return True
                    tmp = size - 1 - d[k]
                    return self.match(s, p, ss - tmp, d[k] + 1, tmp)
                i += d[k] - j;
                j = d[k] + 1;
                k += 1
                if i == ss:
                    while j < size:
                        if p[j] != '*':
                            return False
                        j += 1
                    return True
            elif first:
                return False
            else:
                i += 1
        return False
运行结果:
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值