Skip to content

[leetcode] 10. Regular Expression Matching

Published: at 07:27 AM (4 min read)

Table of Contents

Open Table of Contents

Description

Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where:

The matching should cover the entire input string (not partial).

Example 1:

Input: s = "aa", p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Example 2:

Input: s = "aa", p = "a*"
Output: true
Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".

Example 3:

Input: s = "ab", p = ".*"
Output: true
Explanation: ".*" means “zero or more (*) of any character (.)”.

Constraints:

Approach

Approach

Use dynamic programming to solve the problem. The idea is to create a 2D DP table where dp[i][j] represents whether the first i characters of the string s match the first j characters of the pattern p.

First, we initialize the DP table with an extra row and column to handle the empty string cases. We also preprocess the pattern p to combine characters with '*' into single units. This helps in handling the repetition cases more effectively.

The DP table is then filled based on the following rules:

  1. Rule 1: If the current pattern has '*' and the previous pattern matched, then dp[i][j] is true.
  2. Rule 2: If the current pattern doesn’t has '*' and the current string character matches, then dp[i][j] is true.
  3. Rule 3: If the current pattern character has '*', the previous string character matched, and dp[i-1][j] is true, then dp[i][j] is true.

Finally, the value at dp[s.length][p.length] will indicate whether the entire string s matches the pattern p.

Solution

/**
 * @param {string} s
 * @param {string} p
 * @return {boolean}
 */
var isMatch = function (s, p) {
  // Generate labels for string and pattern to handle '*' as a special case.
  const sLabels = generateLabels(s);
  const pLabels = generateLabels(p);
  const dp = Array.from({ length: sLabels.length }, () =>
    Array(pLabels.length).fill(false)
  );

  dp[0][0] = true; // Base case: empty string matches empty pattern

  // Handle patterns that start with '*' since they can match an empty string.
  for (let j = 1; j < pLabels.length; j++) {
    const allowsRepetition = pLabels[j][1] === "*";

    if (allowsRepetition) {
      // Carry forward the match status from the previous pattern element.
      dp[0][j] = dp[0][j - 1];
    }
  }

  // Fill the DP table based on matches between sLabels and pLabels.
  for (let i = 1; i < sLabels.length; i++) {
    for (let j = 1; j < pLabels.length; j++) {
      const currentPattern = pLabels[j];
      // Check if current characters match.
      const currentCharMatch =
        currentPattern[0] === "." || sLabels[i] === currentPattern[0];
      const allowsRepetition = currentPattern[1] === "*";

      if (allowsRepetition) {
        // If '*' is present, it can either:
        // 1. Ignore the '*' and treat it as zero occurrence (dp[i][j - 1]).
        // 2. Use the '*' to match one or more occurrences (dp[i - 1][j] && currentCharMatch).
        dp[i][j] = dp[i][j - 1] || (dp[i - 1][j] && currentCharMatch);
      } else {
        dp[i][j] = dp[i - 1][j - 1] && currentCharMatch;
      }
    }
  }

  return dp[sLabels.length - 1][pLabels.length - 1];
};

const generateLabels = str => {
  const labels = [""];

  for (let i = 0; i < str.length; i++) {
    if (str[i + 1] === "*") {
      labels.push(`${str[i++]}*`);
    } else {
      labels.push(str[i]);
    }
  }

  return labels;
};

Complexity Analysis

Time Complexity

The time complexity is O(m×n)O(m \times n), where mm is the length of the string s and nn is the length of the pattern p.

Space Complexity

The space complexity is O(m×n)O(m \times n), where mm is the length of the string s and nn is the length of the pattern p. The DP table requires O(m×n)O(m \times n) space.


Previous Post
[CSS] 使用 aspect-ratio 讓你在嵌入 youtube, google map 等內容時做到 RWD
Next Post
[Sentry] How to filter out React error #421