Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Dynamic Programming

Regular Expression Matching

Hard · Dynamic Programming · Asked at Google, Meta, Amazon, Microsoft, Uber

Print YES if the pattern p matches the whole string s, otherwise NO. In the pattern:

Input

Two lines: s, then p.

Output

YES or NO.

Constraints

dp[i][j] = s[0..i) matches p[0..j). For p[j − 1] = *: either use zero copies (dp[i][j − 2]) or, if s[i − 1] matches p[j − 2], one more copy (dp[i − 1][j]). Otherwise the characters must match and dp[i][j] = dp[i − 1][j − 1].

Example 1

Input

aa
a

Output

NO

Example 2

Input

aa
a*

Output

YES

Example 3

Input

ab
.*

Output

YES

Hints

  1. Match prefixes: dp[i][j] says whether s[0..i) matches p[0..j).
  2. A starred pair "x*" can match nothing (skip both pattern characters) or one more character of s.
  3. An empty string can still match patterns like abc*.

Approach

dp[0][0] = true; dp[0][j] = dp[0][j − 2] when p[j − 1] is *. For p[j − 1] = *, with x = p[j − 2]: dp[i][j] = dp[i][j − 2] (zero copies) or (x matches s[i − 1] and dp[i − 1][j]) (one more copy — staying at j lets it repeat). Otherwise dp[i][j] = (p[j − 1] is . or equals s[i − 1]) and dp[i − 1][j − 1]. The answer is dp[|s|][|p|].

Complexity: O(|s| · |p|) time · O(|s| · |p|) space

Solution

C++ solution

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

int main() {
    string s, p;
    cin >> s >> p;
    int n = s.size(), m = p.size();
    vector<vector<char>> dp(n + 1, vector<char>(m + 1, 0));
    dp[0][0] = 1;
    for (int j = 2; j <= m; j++)
        if (p[j - 1] == '*') dp[0][j] = dp[0][j - 2];
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++) {
            if (p[j - 1] == '*') {
                char x = p[j - 2];
                dp[i][j] = dp[i][j - 2] || ((x == '.' || x == s[i - 1]) && dp[i - 1][j]);
            } else {
                dp[i][j] = (p[j - 1] == '.' || p[j - 1] == s[i - 1]) && dp[i - 1][j - 1];
            }
        }
    cout << (dp[n][m] ? "YES" : "NO") << "\n";
    return 0;
}

Python solution

import sys

s, p = sys.stdin.read().split()[:2]
n, m = len(s), len(p)
prev = [False] * (m + 1)
prev[0] = True
for j in range(2, m + 1):
    if p[j - 1] == "*":
        prev[j] = prev[j - 2]
for i in range(1, n + 1):
    cur = [False] * (m + 1)
    c = s[i - 1]
    for j in range(1, m + 1):
        pj = p[j - 1]
        if pj == "*":
            x = p[j - 2]
            cur[j] = cur[j - 2] or ((x == "." or x == c) and prev[j])
        else:
            cur[j] = (pj == "." or pj == c) and prev[j - 1]
    prev = cur
print("YES" if prev[m] else "NO")

Java solution

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String s = br.readLine().trim(), p = br.readLine().trim();
        int n = s.length(), m = p.length();
        boolean[][] dp = new boolean[n + 1][m + 1];
        dp[0][0] = true;
        for (int j = 2; j <= m; j++)
            if (p.charAt(j - 1) == '*') dp[0][j] = dp[0][j - 2];
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= m; j++) {
                char pj = p.charAt(j - 1);
                if (pj == '*') {
                    char x = p.charAt(j - 2);
                    dp[i][j] = dp[i][j - 2] || ((x == '.' || x == s.charAt(i - 1)) && dp[i - 1][j]);
                } else {
                    dp[i][j] = (pj == '.' || pj == s.charAt(i - 1)) && dp[i - 1][j - 1];
                }
            }
        System.out.println(dp[n][m] ? "YES" : "NO");
    }
}

Solve Regular Expression Matching online · All practice problems