Algo-Sim › Advanced DP

Wildcard Matching

Hard · Advanced DP · step through it in Java, Python and C++ on your own input

Match s against a pattern with '?' and '*'. A 2D table of prefix pairs: '*' matches nothing (left) or one more letter (up).

Problem

Implement wildcard matching of a string s against a pattern p, where ? matches any single character and * matches any sequence of characters, including the empty one. The pattern must match the whole string.

Constraints

Edge cases to test

Follow-up questions

Is there a greedy method?
Remember the last star and the position it matched; on a mismatch, let that star eat one more letter. O(m·n) worst case, O(1) space.
How does it differ from Regular Expression Matching?
Here * stands alone and matches any run; there * repeats the previous character.

Solution

Java

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

Python

def is_match(s, p):
    m, n = len(s), len(p)
    dp = [[False] * (n + 1) for _ in range(m + 1)]
    dp[0][0] = True
    for j in range(1, n + 1):
        dp[0][j] = p[j - 1] == "*" and dp[0][j - 1]
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if p[j - 1] == "*":
                dp[i][j] = dp[i][j - 1] or dp[i - 1][j]
            else:
                fits = p[j - 1] == "?" or p[j - 1] == s[i - 1]
                dp[i][j] = fits and dp[i - 1][j - 1]
    return dp[m][n]

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    bool isMatch(string &s, string &p) {
        int m = int(s.size()), n = int(p.size());
        vector<vector<bool>> dp = vector<vector<bool>>(m + 1, vector<bool>(n + 1));
        dp[0][0] = true;
        for (int j = 1; j <= n; j++)
            dp[0][j] = p[j - 1] == '*' && dp[0][j - 1];
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                char pc = p[j - 1];
                if (pc == '*') {
                    dp[i][j] = dp[i][j - 1] || dp[i - 1][j];
                } else {
                    bool fits = pc == '?' || pc == s[i - 1];
                    dp[i][j] = fits && dp[i - 1][j - 1];
                }
            }
        }
        return dp[m][n];
    }
};

More Advanced DP problems