Given a string and a pattern containing wildcard characters, write an efficient algorithm to check if the string matches with the wildcard pattern or not.

The ? wildcard character can match any character in the input string, and the * wildcard character can match to zero or more characters in the input string.

 
For example,

Input:  string = XYXZZXY, pattern = X***Y
Output: true
 
Input:  string = XYXZZXY, pattern = X***X
Output: false
 
Input:  string = XYXZZXY, pattern = X***X?
Output: true
 
Input:  string = XYXZZXY, pattern = *
Output: true

Practice this problem

The idea is to solve this problem by dividing the problem into subproblems recursively. For a given pattern[0…m] and word[0…n],

  1. If pattern[m] == *, if * matches the current character in the input string, move to the next character in the string; otherwise, ignore the * character and move to the next character in the pattern.
  2. If pattern[m] == ?, ignore the current characters of both string and pattern and check if pattern[0…m-1] matches word[0…n-1].
  3. If the current character in the pattern is not a wildcard character, it should match the current character in the input string.

Special care has to be taken to handle base conditions:

  1. If both the input string and pattern reach their end, return true.
  2. If only the pattern reaches its end, return false.
  3. If only the input string reaches its end, return true only when the remaining characters in the pattern consists of all *.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

The time complexity of the above solution is exponential and occupies space in the call stack. dynamic programming can bring down the time complexity to O(m.n) using O(m.n) extra space, where m is the length of the string and n is the length of the pattern. The dynamic programming solution is demonstrated below in C++, Java, and Python using memoization:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Exercise: Implement dynamic programming solution using tabulation.