Skip to content

Regular Expression II

Logical Breakdown

  • [ ] Subproblem Identification:
  • [ ] Optimal Substructure:
  • [ ] Constraint Handling: (e.g., Modulo \(10^9 + 7\))
  • [ ] Optimization: (Matrix Exponentiation if 'A' is huge)

Mathematical Rigor

State Definition

Let \(dp[i]\) be the state for the \(i\)-th subproblem.

Recurrence Relation

\[ dp[i] = ... \]

Visualization

graph TD A["Current State"] --> B["Previous State 1"] A --> C["Previous State 2"]

Complexity Analysis

Approach Time Complexity Space Complexity
Iterative DP \(O(N)\) \(O(1)\)

Code Reference

package com.dsa.dynamic_programming;

import java.util.*;

/ * Problem: Regular Expression II * Group: 11. Dynamic Programming */ / * ============================================================================================ * PROBLEM: Regular Expression Match II (Formal Regex) * ============================================================================================ * * --------------------- * 1. Problem Description * --------------------- * Implement regex matching: * '.' : Matches any single character. * '' : Matches zero or more of the PRECEDING element. * (e.g., "c" matches "", "c", "cc", "ccc"). * * --------------------- * 2. Logical Breakdown * --------------------- * Let dp[i][j] = match S[0..i-1] with P[0..j-1]. * * Logic for P[j-1]: * 1. If P[j-1] is '.' or matches S[i-1]: * dp[i][j] = dp[i-1][j-1] * * 2. If P[j-1] is '': * The '' applies to the character P[j-2] (let's call it 'prev'). * * Case A (Zero occurrences of 'prev'): * We ignore 'prev' entirely (move pattern back by 2). * -> dp[i][j-2] * * Case B (One or more occurrences): * We can only do this if S[i-1] matches 'prev' (or 'prev' is '.'). * If valid, we consume one character of S, but keep the '' in P to allow matching more. * -> dp[i-1][j] * * dp[i][j] = (Case A) || (Matches(S[i-1], P[j-2]) && Case B) * * ============================================================================================ */ public class RegularExpressionII { public int solve(int A) { // TODO: Implement solution return 0; }

public int isMatchRegex(String aa, String s) {
    return 1;
}

}