Skip to content

  • Home
    • Featured Questions
    • Latest Updates
  • Subjects
    • Mathematics
    • Science
    • Computers
    • English
    • General Knowledge
    • History
  • Tips & Strategies
    • Test taking strategy
    • Stress Management
    • Time Management
  • Tools & Utilities
    • Generate Speech From Text
    • Change Your Voice
    • Generate Image From Text
    • Compress Your Images
  • Contact
    • Privacy Policy
    • Mission & Vision
  • Toggle search form

LeetCode Hard – Wildcard Matching

Posted on February 10, 2024 By allexamprep.com No Comments on LeetCode Hard – Wildcard Matching

Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where:

  • '?' Matches any single character.
  • '*' Matches any sequence of characters (including the empty sequence).

The matching should cover the entire input string (not partial).

Example 1:Input: s = “aa”, p = “a” Output: false Explanation: “a” does not match the entire string “aa”.

Example 2:Input: s = “aa”, p = “*” Output: true Explanation: ‘*’ matches any sequence.

Example 3:Input: s = “cb”, p = “?a” Output: false Explanation: ‘?’ matches ‘c’, but the second letter is ‘a’, which does not match ‘b’.

Java Solution

You can implement wildcard pattern matching using dynamic programming. Here’s a Java solution for the given problem:

public class WildcardMatching {
    public static 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 - 1][j] || dp[i][j - 1];
                } 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];
    }

    public static void main(String[] args) {
        System.out.println(isMatch("aa", "a"));    // Output: false
        System.out.println(isMatch("aa", "*"));    // Output: true
        System.out.println(isMatch("cb", "?a"));   // Output: false
    }
}

This solution uses a 2D array dp to store the intermediate results. The entry dp[i][j] represents whether the first i characters of string s match the first j characters of pattern p. The dynamic programming approach efficiently computes the solution in O(m * n) time complexity, where m and n are the lengths of the input strings s and p, respectively.

Python Solution

def isMatch(s, p):
    m, n = len(s), len(p)
    
    # Initialize a 2D array for dynamic programming
    dp = [[False] * (n + 1) for _ in range(m + 1)]
    dp[0][0] = True

    # Handle patterns with '*' at the beginning
    for j in range(1, n + 1):
        if p[j - 1] == '*':
            dp[0][j] = dp[0][j - 1]

    # Dynamic programming to fill the rest of the array
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if p[j - 1] == '*':
                dp[i][j] = dp[i - 1][j] or dp[i][j - 1]
            elif p[j - 1] == '?' or s[i - 1] == p[j - 1]:
                dp[i][j] = dp[i - 1][j - 1]

    return dp[m][n]

# Test cases
print(isMatch("aa", "a"))    # Output: False
print(isMatch("aa", "*"))    # Output: True
print(isMatch("cb", "?a"))   # Output: False

This Python code follows the same dynamic programming approach as the Java solution. It uses a 2D array dp to store intermediate results and determines whether the entire input string s matches the pattern p.

LEETCode Tags:LeetCode Hard

Post navigation

Previous Post: Mineral Nutrition MCQ
Next Post: LeetCode Hard – N-Queens

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Seminar Topic: “Adversarial Machine Learning: Challenges, Defense Mechanisms, and Real-World Implications”
  • Title: Exploring Explainable Artificial Intelligence (XAI) in Deep Learning
  • Project: Simple Weather App with OpenWeatherMap API
  • Project: Web Scraping Quotes with BeautifulSoup
  • Project: Automated Document Summarization with Gensim

Recent Comments

  1. Mystic Knightt on How to get generated id in spring batch template insert
  2. Sachin on How to get generated id in spring batch template insert

Archives

  • February 2024
  • January 2024

Categories

  • Biology
  • Blog
  • Computer QnA
  • LEETCode
  • Projects
  • Privacy Policy
  • Terms Of Service
  • Contact
  • About Us

Copyright © 2025 .

AllExamPrep