Leetcode 44. Wildcard matching | Python


44. Wildcard matching

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


Given a string (s) and a character pattern (P), a wildcard matching supporting ‘?’ and ‘*’ is implemented.

'?' can match any single character.
'*' can match any string (including empty string).
Only when two strings match completely is the match successful.


  • S may be empty and contain only lowercase letters from a to Z.
  • P may be empty and contain only lowercase letters from a to Z, as well as the characters? And *.

Example 1:

s = "aa"
p = "a"
Output: false
Explanation: 'a' cannot match the entire string of 'AA'.

Example 2:

s = "aa"
p = "*"
Output: true
Explanation: '*' can match any string.

Example 3:

s = "cb"
p = "?a"
Output: false
Explanation: '?' can match 'C', but the second 'a' cannot match 'B'.

Example 4:

s = "adceb"
p = "*a*b"
Output: true
Explanation: the first '*' can match the empty string, and the second '*' can match the string "DCE"

Example 5:

s = "acdcb"
p = "a*c?b"
Output: false

Thinking of solving problems

Idea: dynamic planning

This problem is similar to 10. Regular expression matching. About【10. Regular expression matching】You can read through the following links:

Leetcode 10. Regular expression matching | Python

But there are some differences between the two questions. 【10. Regular expression matching】The character pattern of this questionpIs not a separate character, for example:.*The correlation between the two will form a new matching pattern. And in this question,pThe characters of are independent and not associated with the front and back.

First look at the title description, where the character modepThere are the following situations:

  • a-zIn this case, only the corresponding lowercase letters are corresponding
  • ?Can match any single character (that is, any letter)
  • *To match any string (including empty string, that is, it can match 0 or more characters)

Use of this questiondynamic programmingFirst define the state and use thedp[i][j]expresssThe first I strings and patterns ofpWhether the first j strings of match. Then, the following situations will be encountered during state transition:

  • Ifp[j-1] == s[i-1]perhapsp[j-1] == '?'If the current i-th character is matched, thendp[i][j]Can be determined bydp[i-1][j-1]It’s transformed.
  • Ifp[j-1] == '*'Indicates that 0 or more characters can be matched. thatdp[i][j]Can be determined bydp[i][j-1]perhapsdp[i-1][j]It’s transferred. The details are as follows:

    • When using asterisk matching,dp[i][j]Can be determined bydp[i-1][j]Transferred from
    • When asterisk matching is not used,dp[i][j]Can be determined bydp[i][j-1]Transferred from

Therefore, the state transfer equation is as follows:

Leetcode 44. Wildcard matching | Python

Now start the initialization, but here you need to pay attention to the boundary problem:

  • initializationdp[0][0]=True, which means that when the string s and the character pattern P are empty, it means that they can be matched;
  • dp[i][0]Indicates that the character pattern P is empty and cannot match a non empty string, which must be false; (initial DP is false)
  • dp[0][j]This means that the character pattern P is not empty and matches an empty string. Here, only the first j characters of the character pattern are asterisks*Can be set up, so it also needs to be initialized separately.

The specific code implementation is as follows.

code implementation

class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        s_length = len(s)
        p_length = len(p)

        #Initialize DP
        dp = [[False] * (p_length+1) for _ in range(s_length + 1)]

        #Initialize DP[0][0],表示空模式匹配空字符串
        dp[0][0] = True

        #Initialize DP[0][j],非空模式匹配空字符串
        for j in range(1, p_length+1):
            if p[j-1] != "*":
            dp[0][j] = True
        for i in range(1, s_length+1):
            for j in range(1, p_length+1):
                #Substituting transfer equation
                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-1][j] or dp[i][j-1]
        return dp[s_length][p_length]

Implementation results

Leetcode 44. Wildcard matching | Python

Article original, welcome to pay attention to praise. The official account of WeChat is updated in parallel.

Leetcode 44. Wildcard matching | Python