26. Wildcard Pattern Matching
The problem can be found at the following link: Question Link
Note: Sorry for uploading late, my exam is going on.
Problem Description
Given two strings, pattern and str, which may be of different sizes, return 1 if the wildcard pattern matches str, else return 0. The wildcard pattern can include the characters ? and *.
?matches any single character.*matches any sequence of characters (including the empty sequence).
Note: The matching should cover the entire string str (not partial matches).
Example:
Input:
pattern = "ba*a?"
str = "baaabab"Output:
1Explanation: Replace * with "aab" and ? with "b".
My Approach
Dynamic Programming (DP) Setup:
Create a 2D DP array where
dp[i][j]will be1if the firsticharacters inpatternmatch the firstjcharacters instr, else0.
Initialization:
dp[0][0] = 1because an empty pattern matches an empty string.If
pattern[j-1]is*, thendp[j]can inherit the value fromdp[j-1]since*can represent an empty sequence.
DP Array Population:
For each character in
strandpattern, update the DP array:If
pattern[j-1]is?orpattern[j-1]matchesstr[i-1], then setnewDp[j] = dp[j-1].If
pattern[j-1]is*, setnewDp[j] = dp[j] || newDp[j-1], allowing*to match multiple characters.
Final Answer:
The value of
dp[n]will determine if the entirestrmatches thepattern.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n*m), where
nis the length ofstrandmis the length ofpattern, as we iterate over all possible pairs of characters.Expected Auxiliary Space Complexity: O(n*m), due to the DP array that stores matching results for all substrings.
Code (C++)
Code (Java)
Code (Python)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit my LinkedIn:- Any Questions. Thank you for your input; together, we strive to create a space where learning is a collaborative endeavor.
⭐ Star this repository if you find it helpful or intriguing! ⭐
📍Visitor Count
Last updated