Sign in with Google

Google will share your name, email, and profile picture with DevExCode. See our privacy policy.

LeetCode 44: Wildcard Matching

LeetCode 44 Solution Explanation

Explanation

To solve this problem, we can use a dynamic programming approach with a 2D dp array. We will iterate over the input string s and the pattern string p to fill in the dp array. At each step, we will consider the current characters in s and p and update the dp array based on the following conditions:

  1. If the characters match or the pattern character is '?', we take the value from the diagonal element in the dp array.
  2. If the pattern character is '*', we consider two possibilities - either we take the value from the left element or from the top element in the dp array.
  3. If none of the above conditions apply, we mark the current dp cell as false.

Finally, the value in the bottom right cell of the dp array will indicate whether the entire input string matches the pattern.

  • Time complexity: O(m*n) where m is the length of input string s and n is the length of the pattern p.
  • Space complexity: O(m*n) for the dp array.

LeetCode 44 Solutions in Java, C++, Python

class Solution {
    public boolean isMatch(String s, String p) {
        int m = s.length();
        int n = p.length();
        
        boolean[][] dp = new boolean[m + 1][n + 1];
        dp[0][0] = true;
        
        for (int j = 1; j <= n; j++) {
            if (p.charAt(j - 1) == '*') {
                dp[0][j] = dp[0][j - 1];
            }
        }
        
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (p.charAt(j - 1) == '*' ) {
                    dp[i][j] = dp[i][j - 1] || dp[i - 1][j];
                } else if (p.charAt(j - 1) == '?' || s.charAt(i - 1) == p.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1];
                }
            }
        }
        
        return dp[m][n];
    }
}

Interactive Code Editor for LeetCode 44

Improve Your LeetCode 44 Solution

Use the editor below to refine the provided solution for LeetCode 44. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems