LeetCode 10: Regular Expression Matching Solution

Master LeetCode problem 10 (Regular Expression Matching), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

10. Regular Expression Matching

Problem Explanation

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()].

Solution Code

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];
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 10 (Regular Expression Matching)?

This page provides optimized solutions for LeetCode problem 10 (Regular Expression Matching) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 10 (Regular Expression Matching)?

The time complexity for LeetCode 10 (Regular Expression Matching) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 10 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 10 in Java, C++, or Python.

Back to LeetCode Solutions