← Home

44. Wildcard Matching

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
dynamic programmingC++Markdown
44

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 44. Wildcard Matching, the solution in this repository is mainly a dynamic programming solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: dynamic programming, greedy.

The notes already sitting in the source point us in the right direction:

  • recursion
  • TLE
  • 939 / 1809 test cases passed.

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are isMatch.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • Substring checks are convenient but not free, so they are part of the real complexity story.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//recursion
02//TLE
03//939 / 1809 test cases passed.
04class Solution {
05public:
06    bool isMatch(string s, string p) {
07        if(p.size() == 0) return s.size() == 0;
08
09        bool first_match = (s.size() > 0) && (p[0] == s[0] || p[0] == '?' || p[0] == '*');
10
11        if(p[0] == '*'){
12            return first_match && isMatch(s.substr(1), p) ||
13                isMatch(s, p.substr(1));
14        }else{
15            //includes the case when p[0] is equal to '?'
16            return first_match && isMatch(s.substr(1), p.substr(1));
17        }
18    }
19};
20
21//recursion + memorization
22//Runtime: 68 ms, faster than 58.99% of C++ online submissions for Wildcard Matching.
23//Memory Usage: 28 MB, less than 11.54% of C++ online submissions for Wildcard Matching.
24class Solution {
25public:
26    vector<vector<int>> memo;
27    string s, p;
28    
29    bool isMatch(int i, int j){
30        //p empty
31        if(j == p.size()) return i == s.size();
32        
33        if(memo[i][j] != -1){
34            return memo[i][j];
35        }
36        
37        bool first_match = (i < s.size()) && (p[j] == s[i] || p[j] == '?' || p[j] == '*');
38        
39        if(p[j] == '*'){
40            memo[i][j] = (first_match && isMatch(i+1, j)) || isMatch(i, j+1);
41        }else{
42            memo[i][j] = first_match && isMatch(i+1, j+1);
43        }
44        
45        return memo[i][j];
46    }
47    
48    bool isMatch(string s, string p) {
49        this->s = s;
50        this->p = p;
51        int m = s.size(), n = p.size();
52        memo = vector<vector<int>>(m+1, vector(n+1, -1));
53        
54        return isMatch(0, 0);
55    }
56};
57
58//DP
59//Runtime: 228 ms, faster than 27.30% of C++ online submissions for Wildcard Matching.
60//Memory Usage: 11.1 MB, less than 46.15% of C++ online submissions for Wildcard Matching.
61class Solution {
62public:
63    bool isMatch(string s, string p) {
64        int m = s.size(), n = p.size();
65        vector<vector<bool>> dp(m+1, vector(n+1, false));
66        
67        //base case: both empty
68        dp[m][n] = true;
69        /*
70        dp[i][n] is always false for i not equal to m,
71        because at that time, s is not empty and p is empty
72        */
73        
74        for(int i = m; i >= 0; i--){
75            for(int j = n-1; j >= 0; j--){
76                bool first_match = (i < m) && (p[j] == s[i] || p[j] == '?' || p[j] == '*');
77                
78                if(p[j] == '*'){
79                    dp[i][j] = (first_match && dp[i+1][j]) || dp[i][j+1];
80                }else{
81                    dp[i][j] = first_match && dp[i+1][j+1];
82                }
83            }
84        }
85        
86        return dp[0][0];
87    }
88};
89
90//greedy
91//https://leetcode.com/problems/wildcard-matching/discuss/17810/Linear-runtime-and-constant-space-solution
92//Runtime: 8 ms, faster than 95.12% of C++ online submissions for Wildcard Matching.
93//Memory Usage: 6.6 MB, less than 100.00% of C++ online submissions for Wildcard Matching.
94class Solution {
95public:
96    bool isMatch(string s, string p) {
97        int i = 0, j = 0;
98        int m = s.size(), n = p.size();
99        int last_match = -1, starj = -1;
100        
101        while(i < m){
102            // cout << s[i] << ", " << ((j < n) ? p[j] : ' ') << endl;
103            // cout << i << ", " << j << ", starj: " << starj << ", last_match: " << last_match << endl;
104            if(j < n && (p[j] == s[i] || p[j] == '?')){
105                //match one
106                i++;
107                j++;
108            }else if(j < n && p[j] == '*'){
109                //greedily match one
110                starj = j;
111                last_match = i;
112                j++;
113                //why not i++?
114            }else if(starj != -1){
115                //not match, fallback to use previous found '*'
116                last_match++; //the previous star now matches s[last_match+1]
117                i = last_match; //?
118                j = starj+1; //now start from the next char of previous '*'
119            }else{
120                //current char not match, and cannot fallback
121                // cout << endl;
122                return false;
123            }
124        }
125        // cout << endl;
126        
127        //if the remaining char in p are all '*', we think it's a match
128        return p.substr(j) == string(p.size()-j, '*');
129    }
130};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.