标签:leetcode
问题描述:
给定字符串s与模式串p,其中p中的‘?‘可以匹配任意单个字符,‘*‘可以匹配任意字符串(包括空串),判断模式串是否匹配字符s全部(不是部分)。
例子:
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
思路:动态规划
字符串s: s1s2...sm 模式串p: p1p2...pn
递归子问题:如果sm与pn相同或者pn是‘?‘,那么问题归为判断s1s2...sm-1与p1p2...pn-1是否匹配。如果pn为‘*‘,如果‘*‘匹配空串,那么问题归为判断s1s2...sm与p1p2...pn-1是否匹配,如果‘*‘不匹配空串,那么问题归为s1s2...sm-1与p1p2...pn是否匹配子问题。
终止条件:当字符串s为空时,如果p为空或者p中都是‘*‘返回真,否则返回假。
代码:Python
class Solution:
    # @param s, an input string
    # @param p, a pattern string
    # @return a boolean
    def __init__(self):
        self.mark2D = []
        
    def isMatch(self, s, p):
        self.mark2D = [[-1 for i in range(1024)] for j in range(1024)]
        self.isMatch1(s, p)
        
    def isMatch1(self, s, p):
        if self.mark2D[len(s)][len(p)] != -1:
            return self.mark2D[len(s)][len(p)]
        ret = False
        if len(s) == 0:
            if len(p) == 0 or (p[0] == ‘*‘ and len(set(p)) == 1):
                ret = True
            else:
                ret = False
        elif len(p) == 0:
            ret = False
        elif s[-1] == p[-1] or p[-1] == ‘?‘:
            ret = self.isMatch1(s[0:-1], p[0:-1])
        elif p[-1] == ‘*‘:
            if self.isMatch1(s, p[0:-1]):
                ret = True
            else:
                ret = self.isMatch1(s[0:-1], p)
        else:
            ret = False
        self.mark2D[len(s)][len(p)] = ret
        return ret;
本文出自 “8339141” 博客,请务必保留此出处http://8349141.blog.51cto.com/8339141/1626620
leetcode解题报告:44 Wildcard Matching
标签:leetcode
原文地址:http://8349141.blog.51cto.com/8339141/1626620