Here is a standard Dynamic Programming solution for LeetCode 10 (Regular Expression Matching) in Java.
Approach
We use a 2D boolean array
“dp[i][j]” which represents whether the first
“i” characters of the string
“s” match the first
“j” characters of the pattern
“p”.
Key Rules:
- Base Case:
“dp[0][0] = true” (empty matches empty). - Pattern ends with
“''": The
"” can match zero of the preceding element (
“dp[i][j-2]”) OR one/more if the preceding character matches (
“dp[i-1][j]”). - Normal match /
“‘.’”: If characters match or pattern is
“‘.’”, carry over the previous state (
“dp[i-1][j-1]”).
Java Implementation
class Solution {
public boolean isMatch(String s, String p) {
int m = s.length();
int n = p.length();
// dp[i][j] = true if first i chars of s match first j chars of p boolean[][] dp = new boolean[m + 1][n + 1]; // 1. Base case: empty string matches empty pattern dp[0][0] = true; // 2. Handle patterns like a*, a*b*, a*b*c* matching an empty string for (int j = 2; j <= n; j++) { if (p.charAt(j - 1) == '*') { dp[0][j] = dp[0][j - 2]; } } // 3. Fill the DP table for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { char currentCharS = s.charAt(i - 1); char currentCharP = p.charAt(j - 1); // Case A: Current characters match or pattern has '.' if (currentCharP == currentCharS || currentCharP == '.') { dp[i][j] = dp[i - 1][j - 1]; } // Case B: Current pattern character is '*' else if (currentCharP == '*') { // '*' matches zero of the preceding element dp[i][j] = dp[i][j - 2]; // '*' matches one or more of the preceding element // Check if the character before '*' matches current string char char charBeforeStar = p.charAt(j - 2); if (charBeforeStar == currentCharS || charBeforeStar == '.') { dp[i][j] = dp[i][j] || dp[i - 1][j]; } } // Case C: Characters don't match else { dp[i][j] = false; } } } return dp[m][n]; }}
Complexity Analysis
- Time Complexity: O(m \times n) , where m is the length of
“s” and nis the length ofp`. We fill a table of size (m+1) \times (n+1)$. - Space Complexity: O(m \times n) for the DP table. (This can be optimized to O(n) using a 1D array if needed.)
Test Cases
“s”
“p” Output
““aa””
““a””
“false”
““aa””
““a*””
“true”
““ab””
“”.*“”
“true”
““aab””
““cab””
“true”
““mississippi””
““misisp*.””
“false”
Would you like me to explain a specific part of the logic in more detail, or provide the space-optimized (1D DP) version?