![]() |
VOOZH | about |
Given two strings 'str' and a wildcard pattern 'pattern' of length n and m respectively, the task is to return '1' if the wildcard pattern is matched with str else return '0'. All characters of the string str and pattern always belong to the alphanumeric characters.
Pre-requisite: Dynamic Programming | Wildcard Pattern Matching
Examples:
Input: pattern = "ba*a?", str = "baaabab"
Output: 1
Explanation: Replace '*' with "aab" and '?' with 'b'.Input: pattern = "a*ab", str = "baaabab"
Output: 0
Explanation: Because in string pattern character 'a' at first position, pattern and str can't be matched.
The ‘?‘ character is straightforward as it matches any single character, which means whenever ‘?’ appears in the pattern, it corresponds to any character in the input string. The ‘*’ character, however, can represent any sequence of characters, including the empty sequence. This introduces complexity because ‘*’ can potentially match zero, one, two, or more characters.
The main idea to solve this problem efficiently is to use a greedy backtracking approach instead of trying all possible expansions of ‘*’. By using two pointers to traverse the string and the pattern, our solution would records the position of the last ‘*’ encountered and the corresponding position in the string. Initially, ‘*’ is assumed to match zero characters, but if a mismatch occurs later, the solution backtracks and assumes ‘*’ matches one more character, and continues this process iteratively. This greedy strategy reduces unnecessary checks and computations, making the solution more efficient. After traversing the string, our solution would make sure that any remaining characters in the pattern are all ‘*’, which can match an empty sequence.
Step-by-Step Implementation:
1
Time complexity: O(s+p), where s and p are lengths of the input string and the pattern correspondingly
Auxiliary Space: O(1) since it's a constant space solution.