您的位置:首页 > 其它

LeetCode Wildcard Matching

2016-01-22 19:48 302 查看

LeetCode解题之Wildcard Matching

原题

万用字符通配符的字符串匹配判断。”?”表示一个任意的字符,”*”表示任意多个字符。判断目标字符串是否与模式串相匹配。

注意点:

整个目标字符串要全部匹配进去,不能只匹配部分

例子:

输入: s = “abc”, p = “a*b*e”

输出: False

解题思路

Regular Expression Matching 同类型的题,不过换了不同类型的通配符。刚开始写了一个动态规划,结果超时了,转换了下思路,改用回溯法。用两个指针分别来表示目标串和模式串遍历到的当前位置,如果两个字符相等(考虑”?”通配符),则继续前进,如果是”*”通配符,那么要记录下目标字符串当前位置,及模式串下一个位置,现在假设的是”*”用来匹配0个字符,继续尝试匹配,如果后面出现不匹配的情况,那么应该回退到这两个位置(目标串的位置要向后移一位,否则会不断回退到原来的位置),发生一次回退,代表着”*”要多匹配掉一个字符。按照这种方式不断尝试匹配,直到目标串都已经匹配掉或者匹配失败(匹配串中没有”*”,且不能匹配整个目标串)。这时候要看看匹配串是否还有剩余除了”*”以外的字符。如果最终匹配串都全部遍历完了,那么说明匹配成功。

AC源码

[code]class Solution(object):
    def isMatch(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: bool
        """
        p_index, s_index, last_s_index, last_p_index = 0, 0, -1, -1
        while s_index < len(s):
            # Normal match including '?'
            if p_index < len(p) and (s[s_index] == p[p_index] or p[p_index] == '?'):
                s_index += 1
                p_index += 1
            # Match with '*'
            elif p_index < len(p) and p[p_index] == '*':
                p_index += 1
                last_s_index = s_index
                last_p_index = p_index
            # Not match, but there is a '*' before
            elif last_p_index != -1:
                last_s_index += 1
                s_index = last_s_index
                p_index = last_p_index
            # Not match and there is no '*' before
            else:
                return False
        # Check if there is still character except '*' in the pattern
        while p_index < len(p) and p[p_index] == '*':
            p_index += 1
        # If finish scanning both string and pattern, then it matches well
        return p_index == len(p)

if __name__ == "__main__":
    assert Solution().isMatch("aa", "a") == False
    assert Solution().isMatch("aa", "aa") == True
    assert Solution().isMatch("aaa", "aa") == False
    assert Solution().isMatch("aa", "*") == True
    assert Solution().isMatch("aa", "a*") == True
    assert Solution().isMatch("ab", "?*") == True
    assert Solution().isMatch("aab", "c*a*b") == False


欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: