10. Regular Expression Matching

Explanation

To solve this problem, we can use dynamic programming. We will create a 2D DP array where dp[i][j] will represent whether the pattern p[0...j-1] matches the string s[0...i-1]. We will then fill the DP array based on the following conditions:

  1. If p[j-1] is a normal character or '.' (matches any single character), then dp[i][j] is true if dp[i-1][j-1] is true and s[i-1] matches p[j-1].
  2. If p[j-1] is '*', then we have two cases:
    • If p[j-2] matches s[i-1], then dp[i][j] is true if either dp[i][j-2] (zero occurrences of the preceding element) or dp[i-1][j] (one or more occurrences of the preceding element) is true.

Finally, the result will be stored in dp[s.length()][p.length()].

class Solution {
    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 i = 0; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (j > 1 && p.charAt(j - 1) == '*') {
                    dp[i][j] = dp[i][j - 2] || (i > 0 && (s.charAt(i - 1) == p.charAt(j - 2) || p.charAt(j - 2) == '.') && dp[i - 1][j]);
                } else {
                    dp[i][j] = i > 0 && dp[i - 1][j - 1] && (s.charAt(i - 1) == p.charAt(j - 1) || p.charAt(j - 1) == '.');
                }
            }
        }

        return dp[m][n];
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.