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

来源:互联网 发布:意大利军事实力 知乎 编辑:程序博客网 时间:2024/04/29 15:51

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") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "*") → trueisMatch("aa", "a*") → trueisMatch("ab", "?*") → trueisMatch("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
原创粉丝点击