44 Wildcard Matching

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

solution

class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        dp = [[False] * (len(p) + 1) for _ in range(len(s) + 1)]
        dp[0][0] = True

        for j in range(1, len(p) + 1):
            # 如果前面全都是*开头, 则全都是True
            if p[j-1] != '*':
                break
            dp[0][j] = True
        
        for i in range(1, len(s) + 1):
            for j in range(1, len(p) + 1):
                if p[j-1] == s[i-1] or p[j-1] == '?':
                    dp[i][j] = dp[i-1][j-1]
                elif p[j-1] == '*':
                    # 代表0个或多个, 0个相当于dp[i-1][j], 多个相当于dp[i][j-1]
                    dp[i][j] = dp[i-1][j] or dp[i][j-1]
        return dp[-1][-1]

时间复杂度:O() 空间复杂度:O()

Last updated