LeetCode刷题(21)

来源:互联网 发布:人工智能 教育风口 编辑:程序博客网 时间:2024/06/08 10:13

Wildcard Matching
?匹配单字符
* 匹配任意字符串
采用DP算法,做这类匹配问题

class Solution(object):    def isMatch(self, s, p):        """        :type s: str        :type p: str        :rtype: bool        """        m = len(s)        n = len(p)        dp = []        for i in xrange(m+1):            tmp = []            for j in xrange(n+1):                tmp += False,            dp += tmp,        dp[0][0] = True        for i in range(m+1):            for j in range(1,n+1):                if p[j-1] == '*':                    dp[i][j] = dp[i-1][j] or dp[i][j-1]                elif p[j-1] == '?':                    dp[i][j] = i>0 and dp[i-1][j-1]                else :                    dp[i][j] = i>0 and dp[i-1][j-1] and s[i-1] == p[j-1]        return dp[m][n]