☰
YuanBao LeetCode 10.Regular Expression Matching Java Implement
2026/10/6 2:49:37 网站建设 项目流程

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:

  1. Base Case:
    “dp[0][0] = true” (empty matches empty).
  2. 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]”).
  3. 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?

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询