10. Regex matching
10_solution1_tab.c
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
bool isMatch(char *s, char *p) {
int n = strlen(s), m = strlen(p);
int w = m + 1;
// dp[i * w + j]: does s[i..] match p[j..]?
bool *dp = calloc((n + 1) * w, sizeof(bool));
// base case: empty pattern matches only the empty string
dp[n * w + m] = true; // dp[i][m] for i < n stays false
for (int i = n; i >= 0; i--) { // row i reads row i+1 → bottom-up
for (int j = m - 1; j >= 0; j--) { // reads j+1, j+2 → right-to-left
bool match = i < n && (s[i] == p[j] || p[j] == '.');
if (j + 1 < m && p[j + 1] == '*') {
dp[i * w + j] = dp[i * w + j + 2] || // zero copies of x*
(match && dp[(i + 1) * w + j]); // one more copy
} else {
dp[i * w + j] = match && dp[(i + 1) * w + j + 1];
}
}
}
bool res = dp[0];
free(dp);
return res;
}
10_solution2_memo.c
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
static const char *S, *P;
static int n, m, w;
static int *memo; // memo[i * w + j], -1 = not computed
static bool dpf(int i, int j) {
// pattern used up: match only if the string is used up too
if (j == m)
return i == n;
if (memo[i * w + j] != -1)
return memo[i * w + j];
// does the current pattern char match s[i]? (s may already be used up)
bool match = i < n && (S[i] == P[j] || P[j] == '.');
bool res;
if (j + 1 < m && P[j + 1] == '*') {
// treat "x*" as one unit: either use zero copies (skip it),
// or match one copy and stay on "x*" to allow more
res = dpf(i, j + 2) || (match && dpf(i + 1, j));
} else {
// plain char or '.': must match exactly one character
res = match && dpf(i + 1, j + 1);
}
memo[i * w + j] = res;
return res;
}
bool isMatch(char *s, char *p) {
S = s, P = p, n = strlen(s), m = strlen(p), w = m + 1;
memo = malloc((n + 1) * w * sizeof(int));
for (int k = 0; k < (n + 1) * w; k++)
memo[k] = -1;
bool res = dpf(0, 0);
free(memo);
return res;
}
10_solution1_tab.cpp
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
bool isMatch(string s, string p) {
int n = s.size(), m = p.size();
// dp[i][j]: does s[i..] match p[j..]?
vector<vector<bool>> dp(n + 1, vector<bool>(m + 1, false));
// base case: empty pattern matches only the empty string
dp[n][m] = true; // dp[i][m] for i < n stays false
for (int i = n; i >= 0; i--) { // row i reads row i+1 → bottom-up
for (int j = m - 1; j >= 0; j--) { // reads j+1, j+2 → right-to-left
bool match = i < n && (s[i] == p[j] || p[j] == '.');
if (j + 1 < m && p[j + 1] == '*') {
dp[i][j] = dp[i][j + 2] || // zero copies of x*
(match && dp[i + 1][j]); // one more copy
} else {
dp[i][j] = match && dp[i + 1][j + 1];
}
}
}
return dp[0][0];
}
};
10_solution2_memo.cpp
#include <string>
#include <vector>
using namespace std;
class Solution {
int n, m;
bool dpf(int i, int j, const string &s, const string &p,
vector<vector<int>> &memo) {
// pattern used up: match only if the string is used up too
if (j == m)
return i == n;
if (memo[i][j] != -1)
return memo[i][j];
// does the current pattern char match s[i]? (s may already be used up)
bool match = i < n && (s[i] == p[j] || p[j] == '.');
bool res;
if (j + 1 < m && p[j + 1] == '*') {
// treat "x*" as one unit: either use zero copies (skip it),
// or match one copy and stay on "x*" to allow more
res = dpf(i, j + 2, s, p, memo) || (match && dpf(i + 1, j, s, p, memo));
} else {
// plain char or '.': must match exactly one character
res = match && dpf(i + 1, j + 1, s, p, memo);
}
memo[i][j] = res;
return res;
}
public:
bool isMatch(string s, string p) {
n = s.size(), m = p.size();
vector<vector<int>> memo(n + 1, vector<int>(m + 1, -1));
return dpf(0, 0, s, p, memo);
}
};
10_solution1_tab.go
package dp
func isMatch(s string, p string) bool {
n, m := len(s), len(p)
// dp[i][j]: does s[i..] match p[j..]?
dp := make([][]bool, n+1)
for i := range dp {
dp[i] = make([]bool, m+1)
}
// base case: empty pattern matches only the empty string
dp[n][m] = true // dp[i][m] for i < n stays false
for i := n; i >= 0; i-- { // row i reads row i+1 → bottom-up
for j := m - 1; j >= 0; j-- { // reads j+1, j+2 → right-to-left
match := i < n && (s[i] == p[j] || p[j] == '.')
if j+1 < m && p[j+1] == '*' {
dp[i][j] = dp[i][j+2] || // zero copies of x*
(match && dp[i+1][j]) // one more copy
} else {
dp[i][j] = match && dp[i+1][j+1]
}
}
}
return dp[0][0]
}
10_solution2_memo.go
package dp
func isMatch(s string, p string) bool {
n, m := len(s), len(p)
memo := make([][]int, n+1) // -1 = not computed, 0 = false, 1 = true
for i := range memo {
memo[i] = make([]int, m+1)
for j := range memo[i] {
memo[i][j] = -1
}
}
var dpf func(i, j int) bool
dpf = func(i, j int) bool {
// pattern used up: match only if the string is used up too
if j == m {
return i == n
}
if memo[i][j] != -1 {
return memo[i][j] == 1
}
// does the current pattern char match s[i]? (s may already be used up)
match := i < n && (s[i] == p[j] || p[j] == '.')
var res bool
if j+1 < m && p[j+1] == '*' {
// treat "x*" as one unit: either use zero copies (skip it),
// or match one copy and stay on "x*" to allow more
res = dpf(i, j+2) || (match && dpf(i+1, j))
} else {
// plain char or '.': must match exactly one character
res = match && dpf(i+1, j+1)
}
memo[i][j] = 0
if res {
memo[i][j] = 1
}
return res
}
return dpf(0, 0)
}
10_solution1_tab.java
class Solution {
public boolean isMatch(String s, String p) {
int n = s.length(), m = p.length();
// dp[i][j]: does s[i..] match p[j..]?
boolean[][] dp = new boolean[n + 1][m + 1];
// base case: empty pattern matches only the empty string
dp[n][m] = true; // dp[i][m] for i < n stays false
for (int i = n; i >= 0; i--) { // row i reads row i+1 → bottom-up
for (int j = m - 1; j >= 0; j--) { // reads j+1, j+2 → right-to-left
boolean match = i < n && (s.charAt(i) == p.charAt(j) || p.charAt(j) == '.');
if (j + 1 < m && p.charAt(j + 1) == '*') {
dp[i][j] = dp[i][j + 2] || // zero copies of x*
(match && dp[i + 1][j]); // one more copy
} else {
dp[i][j] = match && dp[i + 1][j + 1];
}
}
}
return dp[0][0];
}
}
10_solution2_memo.java
class Solution {
private int n, m;
private Boolean[][] memo; // null = not computed
private boolean dpf(int i, int j, String s, String p) {
// pattern used up: match only if the string is used up too
if (j == m)
return i == n;
if (memo[i][j] != null)
return memo[i][j];
// does the current pattern char match s[i]? (s may already be used up)
boolean match = i < n && (s.charAt(i) == p.charAt(j) || p.charAt(j) == '.');
boolean res;
if (j + 1 < m && p.charAt(j + 1) == '*') {
// treat "x*" as one unit: either use zero copies (skip it),
// or match one copy and stay on "x*" to allow more
res = dpf(i, j + 2, s, p) || (match && dpf(i + 1, j, s, p));
} else {
// plain char or '.': must match exactly one character
res = match && dpf(i + 1, j + 1, s, p);
}
memo[i][j] = res;
return res;
}
public boolean isMatch(String s, String p) {
n = s.length();
m = p.length();
memo = new Boolean[n + 1][m + 1];
return dpf(0, 0, s, p);
}
}
10_solution1_tab.js
/**
* @param {string} s
* @param {string} p
* @return {boolean}
*/
var isMatch = function (s, p) {
const n = s.length, m = p.length;
// dp[i][j]: does s[i..] match p[j..]?
const dp = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(false));
// base case: empty pattern matches only the empty string
dp[n][m] = true; // dp[i][m] for i < n stays false
for (let i = n; i >= 0; i--) { // row i reads row i+1 → bottom-up
for (let j = m - 1; j >= 0; j--) { // reads j+1, j+2 → right-to-left
const match = i < n && (s[i] === p[j] || p[j] === ".");
if (j + 1 < m && p[j + 1] === "*") {
dp[i][j] = dp[i][j + 2] || // zero copies of x*
(match && dp[i + 1][j]); // one more copy
} else {
dp[i][j] = match && dp[i + 1][j + 1];
}
}
}
return dp[0][0];
};
10_solution2_memo.js
/**
* @param {string} s
* @param {string} p
* @return {boolean}
*/
var isMatch = function (s, p) {
const n = s.length, m = p.length;
const memo = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(-1));
const dpf = (i, j) => {
// pattern used up: match only if the string is used up too
if (j === m) return i === n;
if (memo[i][j] !== -1) return memo[i][j];
// does the current pattern char match s[i]? (s may already be used up)
const match = i < n && (s[i] === p[j] || p[j] === ".");
let res;
if (j + 1 < m && p[j + 1] === "*") {
// treat "x*" as one unit: either use zero copies (skip it),
// or match one copy and stay on "x*" to allow more
res = dpf(i, j + 2) || (match && dpf(i + 1, j));
} else {
// plain char or '.': must match exactly one character
res = match && dpf(i + 1, j + 1);
}
memo[i][j] = res;
return res;
};
return dpf(0, 0);
};
10_solution1_tab.py
class Solution:
def isMatch(self, s: str, p: str) -> bool:
n, m = len(s), len(p)
# dp[i][j]: does s[i..] match p[j..]?
dp = [[False] * (m + 1) for _ in range(n + 1)]
# base case: empty pattern matches only the empty string
dp[n][m] = True # dp[i][m] for i < n stays False
for i in range(n, -1, -1): # row i reads row i+1 → bottom-up
for j in range(m - 1, -1, -1): # reads j+1, j+2 → right-to-left
match = i < n and (s[i] == p[j] or p[j] == ".")
if j + 1 < m and p[j + 1] == "*":
dp[i][j] = dp[i][j + 2] or ( # zero copies of x*
match and dp[i + 1][j] # one more copy
)
else:
dp[i][j] = match and dp[i + 1][j + 1]
return dp[0][0]
10_solution2_memo.py
import sys
from typing import List, Optional
class Solution:
def isMatch(self, s: str, p: str) -> bool:
n, m = len(s), len(p)
sys.setrecursionlimit(max(1000, 2 * (n + m) + 100)) # depth can reach n + m
memo: List[List[Optional[bool]]] = [[None] * (m + 1) for _ in range(n + 1)]
def dpf(i: int, j: int) -> bool:
# pattern used up: match only if the string is used up too
if j == m:
return i == n
if memo[i][j] is not None:
return memo[i][j]
# does the current pattern char match s[i]? (s may already be used up)
match = i < n and (s[i] == p[j] or p[j] == ".")
if j + 1 < m and p[j + 1] == "*":
# treat "x*" as one unit: either use zero copies (skip it),
# or match one copy and stay on "x*" to allow more
res = dpf(i, j + 2) or (match and dpf(i + 1, j))
else:
# plain char or '.': must match exactly one character
res = match and dpf(i + 1, j + 1)
memo[i][j] = res
return res
return dpf(0, 0)
10_solution1_tab.rs
impl Solution {
pub fn is_match(s: String, p: String) -> bool {
let (s, p) = (s.as_bytes(), p.as_bytes());
let (n, m) = (s.len(), p.len());
// dp[i][j]: does s[i..] match p[j..]?
let mut dp = vec![vec![false; m + 1]; n + 1];
// base case: empty pattern matches only the empty string
dp[n][m] = true; // dp[i][m] for i < n stays false
for i in (0..=n).rev() {
// row i reads row i+1 → bottom-up
for j in (0..m).rev() {
// reads j+1, j+2 → right-to-left
let is_match = i < n && (s[i] == p[j] || p[j] == b'.');
dp[i][j] = if j + 1 < m && p[j + 1] == b'*' {
dp[i][j + 2] // zero copies of x*
|| (is_match && dp[i + 1][j]) // one more copy
} else {
is_match && dp[i + 1][j + 1]
};
}
}
dp[0][0]
}
}
10_solution2_memo.rs
impl Solution {
fn dpf(i: usize, j: usize, s: &[u8], p: &[u8], memo: &mut Vec<Vec<Option<bool>>>) -> bool {
let (n, m) = (s.len(), p.len());
// pattern used up: match only if the string is used up too
if j == m {
return i == n;
}
if let Some(res) = memo[i][j] {
return res;
}
// does the current pattern char match s[i]? (s may already be used up)
let is_match = i < n && (s[i] == p[j] || p[j] == b'.');
let res = if j + 1 < m && p[j + 1] == b'*' {
// treat "x*" as one unit: either use zero copies (skip it),
// or match one copy and stay on "x*" to allow more
Self::dpf(i, j + 2, s, p, memo) || (is_match && Self::dpf(i + 1, j, s, p, memo))
} else {
// plain char or '.': must match exactly one character
is_match && Self::dpf(i + 1, j + 1, s, p, memo)
};
memo[i][j] = Some(res);
res
}
pub fn is_match(s: String, p: String) -> bool {
let (s, p) = (s.as_bytes(), p.as_bytes());
let mut memo = vec![vec![None; p.len() + 1]; s.len() + 1];
Self::dpf(0, 0, s, p, &mut memo)
}
}