Tutorialspoint
Problem
Solution
Submissions

Wildcard Pattern Matching

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15
p>Write a C++ program to implement a wildcard pattern matching algorithm. Given an input string `s` and a pattern `p`, implement a function that returns true if the pattern matches the string, and false otherwise. The pattern can include the wildcard character `*` (which matches any sequence of characters, including an empty sequence) and `?` (which matches any single character).
Example 1
  • Input: s = "aa", p = "a"
  • Output: false
  • Explanation:
    • Step 1: Initialize a dynamic programming approach to track matching states.
    • Step 2: Compare the pattern "a" against the string "aa".
    • Step 3: The pattern "a" only matches the first character of "aa".
    • Step 4: Since the pattern doesn't match the entire string, return false.
Example 2
  • Input: s = "adceb", p = "*a*b"
  • Output: true
  • Explanation:
    • Step 1: Initialize a dynamic programming approach to track matching states.
    • Step 2: Process the pattern character by character: - First '*' can match empty string - 'a' matches 'a' in the string - Second '*' can match "dce" - 'b' matches 'b' in the string
    • Step 3: All pattern characters are matched.
    • Step 4: Return true as the pattern successfully matches the entire string.
Constraints
  • 0 ≤ s.length, p.length ≤ 2000
  • s contains only lowercase English letters
  • p contains only lowercase English letters, '?' or '*'
  • Time Complexity: O(m*n) where m is the length of string and n is the length of pattern
  • Space Complexity: O(m*n)
ArraysDynamic Programming KPMGeBay
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use dynamic programming to solve this problem efficiently
  • Create a 2D DP array to track matching status
  • Handle special cases like '*' matching empty sequences
  • Iterate through each character of the string and pattern
  • Consider using a greedy approach for optimization

Steps to solve by this approach:

 Step 1: Create a 2D DP array where dp[i][j] represents if s[0...i-1] matches p[0...j-1].
 Step 2: Handle the base case: an empty pattern matches an empty string.
 Step 3: Pre-process patterns with '*' that can match empty sequences.
 Step 4: Iterate through each character of the string and pattern to fill the DP table.
 Step 5: For '*', consider both matching an empty sequence or matching the current character and extending.
 Step 6: For '?' or matching characters, carry forward the result from previous characters.
 Step 7: The final answer is stored in dp[m][n].

Submitted Code :