Wildcard Matching In C,CPP,JAVA,PYTHON,C#,JS
Problem Statement: Wildcard Matching Given two strings s and p, return true if s matches p (with wildcard characters), and false otherwise. The string p can contain the following wildcard characters: Example: Example 1: Input: s = “aa”, p = “a*”Output: trueExplanation: “a*” matches “aa” because ‘*’ can match the second ‘a’. Example 2: Input: s = “mississippi”, p = “mis*is*p*.”Output: false Example 3: Input: s = “adceb”, p = “*a*b”Output: trueExplanation: The pattern “*a*b” matches the string “adceb”. Approach: The problem can be solved using Dynamic Programming (DP). The idea is to use a 2D DP table where dp[i][j] represents whether the substring s[0..i-1] matches the pattern p[0..j-1]. Steps: Dynamic Programming Solution: Python Code: def isMatch(s: str, p: str) -> bool: # dp[i][j] will be True if s[0…i-1] matches p[0…j-1] dp = [[False] * (len(p) + 1) for _ in range(len(s) + 1)] # Initial condition: empty string matches empty pattern dp[0][0] = True # If the pattern starts with ‘*’ it can match the empty string for j in range(1, len(p) + 1): if p[j – 1] == ‘*’: dp[0][j] = dp[0][j – 1] # Fill the dp table for i in range(1, len(s) + 1): for j in range(1, len(p) + 1): if p[j – 1] == s[i – 1] or p[j – 1] == ‘?’: dp[i][j] = dp[i – 1][j – 1] elif p[j – 1] == ‘*’: dp[i][j] = dp[i – 1][j] or dp[i][j – 1] # The bottom-right corner will contain the answer return dp[len(s)][len(p)] Explanation of the Code: Time and Space Complexity: Example Walkthrough: Example 1: Input: s = “aa”, p = “a*” The final result is True, as dp[2][2] = True. Example 2: Input: s = “mississippi”, p = “mis*is*p*.” Conclusion: The Wildcard Matching problem is efficiently solved using Dynamic Programming. By filling a DP table and considering all possible ways a wildcard can match a sequence of characters, we can determine if the string matches the pattern with wildcards * and ?. The time complexity of O(m * n) is suitable for handling reasonably large inputs, where m and n are the lengths of the string and the pattern, respectively.
Wildcard Matching In C,CPP,JAVA,PYTHON,C#,JS Read More »