Skip to content

044 wildcard matching

44. Wildcard Matching

题目: https://leetcode.com/problems/wildcard-matching/

难度:

Hard

做完Regular Expression Matching来做的这道题,按照DP思路run一下是超时,感觉是开心的,至少暂时没有报错了,有待优化,应该在dp的同时在贪心一下么。

超时代码

class Solution(object):
    def isMatch(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: bool
        """
        m, n = len(s), len(p)
        dp = [ [0 for i in xrange(n+1)] for j in xrange(m+1)]

        dp[0][0] = 1

        # init the first line
        for i in xrange(1,n+1):
            if p[i-1] == '*':
                dp[0][i] = dp[0][i-1]

        for i in xrange(1,m+1):
            for j in xrange(1,n+1):
                if p[j-1] == s[i-1] or p[j-1] == '?':
                    dp[i][j] = dp[i-1][j-1]
                elif p[j-1] == '*':
                    dp[i][j] = dp[i][j-1] or dp[i-1][j]

        return dp[m][n] == 1 

我们一直在努力

apachecn/AiLearning

【布客】中文翻译组