Java String Program · S57
Regular Expression Matching in Java
Write a tiny regex engine: . matches any character and x* matches zero or more copies of x. The star always belongs to the character before it.
Problem Statement
Given a string s and a pattern p, return true if the pattern matches the whole string. In the pattern, . matches any single character and * means zero or more of the preceding element.
The pattern is well formed: every * follows a letter or a dot.
Input/Output Examples
s = "javaaa", p = "java*"OutputtrueExplanation: a* matches the last "aaa" (it could also match zero a's).s = "abc", p = "a.c"OutputtrueExplanation: . matches b.s = "ab", p = ".*c"OutputfalseExplanation: .* can match ab, but nothing matches the required c.Visual Explanation
| s \ p | ∅ | a | * | b |
|---|---|---|---|---|
| ∅ | T | F | T | F |
| a | F | T | T | F |
| a | F | F | T | F |
| b | F | F | F | T |
s = "aab" and p = "a*b": the * column (amber) is true for zero, one and two a's, and the final cell (purple) adds the matching b.For a star, a cell is true if the pair x* is skipped (two columns to the left) or if the current character matches x and the row above is already true in the same column, meaning the star takes one more character.
Approaches
Both approaches use the same two rules for x*: skip it, or use it for one more character. One fills a table; the other recurses with a cache.
Approach 1: Bottom-Up DP Table (Recommended)
Idea: dp[i][j] is true when s[0..i) matches p[0..j).
dp[0][0]is true; patterns such asa*b*also match the empty string.- For
*: true ifdp[i][j - 2](zero copies), or the previous pattern character matchess[i - 1]anddp[i - 1][j]is true. - For
.or an equal letter: copydp[i - 1][j - 1]. - Return
dp[n][m].
Time: O(n × m) · Space: O(n × m).
Approach 2: Top-Down Memoised Recursion
Idea: match(i, j) checks s[i..] against p[j..]; if the next pattern element is starred, try skipping it or consuming one character.
- If the pattern is used up, the string must be too.
- Compute whether the first characters match.
- If
p[j + 1] == '*', returnmatch(i, j + 2)or (firstandmatch(i + 1, j)). - Otherwise, return
firstandmatch(i + 1, j + 1); cache every result.
Time: O(n × m) · Space: O(n × m). Plus recursion depth up to n + m.
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Bottom-Up DP Table (Recommended)
Iterative and free of recursion limits. Each cell uses only cells above or to the left, so a row-by-row fill works.
public class RegexMatchDp {
// dp[i][j] = does s[0..i) match p[0..j)? '.' is any char, 'x*' is zero or more x
static boolean isMatch(String s, String p) {
int n = s.length();
int m = p.length();
boolean[][] dp = new boolean[n + 1][m + 1];
dp[0][0] = true;
for (int j = 2; j <= m; j++) {
dp[0][j] = p.charAt(j - 1) == '*' && dp[0][j - 2]; // "a*b*" can match ""
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
char pc = p.charAt(j - 1);
if (pc == '*') {
char prev = p.charAt(j - 2);
boolean zero = dp[i][j - 2]; // use x* zero times
boolean more = (prev == '.' || prev == s.charAt(i - 1)) && dp[i - 1][j];
dp[i][j] = zero || more;
} else if (pc == '.' || pc == s.charAt(i - 1)) {
dp[i][j] = dp[i - 1][j - 1];
}
}
}
return dp[n][m];
}
public static void main(String[] args) {
String[][] cases = {{"javaaa", "java*"}, {"abc", "a.c"}, {"ab", ".*c"}, {"", "x*y*"}};
for (String[] c : cases) {
System.out.println("s=\"" + c[0] + "\", p=\"" + c[1] + "\" -> " + isMatch(c[0], c[1]));
}
}
}
s="javaaa", p="java*" -> true s="abc", p="a.c" -> true s="ab", p=".*c" -> false s="", p="x*y*" -> true
Time complexity: O(n × m) · Space complexity: O(n × m).
Approach 2: Top-Down Memoised Recursion
Reads almost like the definition of the problem, which makes it the easiest version to derive in an interview.
public class RegexMatchMemo {
// Top-down: match(i, j) asks whether s[i..] matches p[j..]
static boolean isMatch(String s, String p) {
return match(s, p, 0, 0, new Boolean[s.length() + 1][p.length() + 1]);
}
private static boolean match(String s, String p, int i, int j, Boolean[][] memo) {
if (j == p.length()) {
return i == s.length();
}
if (memo[i][j] != null) {
return memo[i][j];
}
boolean first = i < s.length() && (p.charAt(j) == '.' || p.charAt(j) == s.charAt(i));
boolean result;
if (j + 1 < p.length() && p.charAt(j + 1) == '*') {
result = match(s, p, i, j + 2, memo) // skip "x*"
|| (first && match(s, p, i + 1, j, memo)); // use x* once more
} else {
result = first && match(s, p, i + 1, j + 1, memo);
}
return memo[i][j] = result;
}
public static void main(String[] args) {
String[][] cases = {{"javaaa", "java*"}, {"abc", "a.c"}, {"ab", ".*c"}, {"", "x*y*"}};
for (String[] c : cases) {
System.out.println("s=\"" + c[0] + "\", p=\"" + c[1] + "\" -> " + isMatch(c[0], c[1]));
}
}
}
s="javaaa", p="java*" -> true s="abc", p="a.c" -> true s="ab", p=".*c" -> false s="", p="x*y*" -> true
Time complexity: O(n × m) · Space complexity: O(n × m).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Bottom-Up DP Table | O(n × m) | O(n × m) |
| Top-Down Memoised Recursion | O(n × m) | O(n × m) |
Here n is the length of the string and m the length of the pattern. Each of the (n + 1) × (m + 1) states is computed once.
Interview Tips and Recommended Approach
- Treat
x*as one unit. The star never stands alone; always look ahead one character in the pattern. - Initialise the empty-string row. Patterns like
a*b*c*match"". - Compare with wildcard matching. There,
*matches any sequence on its own; here it repeats the previous element. - Start with plain recursion, then add the cache. It shows how the exponential solution becomes polynomial.
Recommended Approach: Bottom-Up DP Table
Why: it is iterative, covers every case explicitly and is easy to test row by row. Many people derive the recursive version first and then convert it to this table.