2020-07-05-每日一题

更多python分类刷题题解代码:请参考github,博客, 知乎

44. 通配符匹配

https://leetcode-cn.com/problems/wildcard-matching/

# 动态规划
# dp[i][j]表示s的前i个字符是否能与p的前j个字符匹配
# 状态转移方程分为如下的几种情况:
#     1、s[i] p[j]均为字母,dp[i][j] = dp[i-1][j-1] and s[i]==p[j]
#     2、p[j] 为?,dp[i][j] = dp[i-1][j-1]
#     3、p[j]为*,分为两种情况,1)这个*不匹配字符,dp[i][j] = dp[i][j-1]
#                             2)这个*号匹配字符,dp[i][j] = dp[i-1][j]
#         综合这种情况dp[i][j] = dp[i-1][j] or dp[i][j-1]
#     边界情况:dp[0][0] = True
#             dp[i][0] = False
#             dp[0][j] = True if p[:j+1] == * else False

class Solution:
    def isMatch(self, s: str, p: str) -> bool:

        if not s and not p: return True
        dp = [[False]*(len(p)+1) for _ in range(len(s)+1)]

        for j in range(len(p)+1):
            if p[:j] == "*" * (j):
                dp[0][j] = True
            else:
                break
        
        for  i in range(1, len(s)+1):
            for j in range(1, len(p)+1):
                if p[j-1] != '?' and p[j-1] != '*':
                    dp[i][j] = dp[i-1][j-1] and s[i-1] == p[j-1]
                elif p[j-1] == '?':
                    dp[i][j] = dp[i-1][j-1]
                else:
                    dp[i][j] = dp[i-1][j] or dp[i][j-1]
        # print(dp)
        return dp[-1][-1]

更多python分类刷题题解代码:请参考github,博客, 知乎

更多技术文章请点击查看

你可能感兴趣的:(leetcode刷题)