LeetSolved

Find solutions to all LeetCode problems here.

44.

Wildcard Matching

Hard

Problem Description

Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '' where: '?' Matches any single character. '' Matches any sequence of characters (including the empty sequence). The matching should cover the entire input string (not partial).

Examples

Input: aa, a
Output: false

Input: aa, *
Output: true

Input: cb, ?a
Output: false

Constraints

Approach to Solve

Use dynamic programming to solve the wildcard matching problem.

Code Implementation

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

Explanation

This solution uses dynamic programming to solve the wildcard matching problem. Here's a detailed explanation of the algorithm:

  1. Initialize a 2D array dp with dimensions (sLen + 1) x (pLen + 1) to store the matching results, where dp[i][j] represents whether the first i characters of s match the first j characters of p.
  2. Set dp[0][0] to true, as an empty pattern matches an empty string.
  3. Iterate through the pattern p to update the dp array:
    • If p[j-1] is '*', set dp[0][j] to dp[0][j-1], indicating that the empty sequence can match the pattern up to the current position.
  4. Iterate through the string s and the pattern p to fill the dp array:
    • If p[j-1] is '*', update dp[i][j] to dp[i][j-1] || dp[i-1][j], indicating that the current sequence can match the pattern up to the current position.
    • If p[j-1] is '?' or s[i-1] matches p[j-1], update dp[i][j] to dp[i-1][j-1], indicating that the current characters match.
  5. Return dp[sLen][pLen], which indicates whether the entire string s matches the pattern p.

The time complexity is O(mn), where m and n are the lengths of the string s and the pattern p, respectively. The space complexity is also O(mn) due to the storage of the dp array.

Complexity

  • Time Complexity: O(m*n)
  • Space Complexity: O(m*n)
Code copied to clipboard!