算法分析與設計課程(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
運行結果:
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章