Skip to content

Commit e6f4a5c

Browse files
authored
Create Regular Expression Matching solution with Recursion
The provided Java code solves the Regular Expression Matching Problem by determining if a given input string s matches a specified pattern p. The pattern can include special characters: 1. " . "matches any single character. 2. " * " matches zero or more occurrences of the preceding character. The implementation uses memoization to store results for string and pattern combinations, enhancing performance, while employing recursive logic to efficiently handle character matching and special characters like . and *.
1 parent 6535d47 commit e6f4a5c

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import java.util.HashMap;
2+
import java.util.Map;
3+
4+
public class Solution {
5+
// Memoization map to store results of subproblems
6+
private Map<String, Boolean> memo = new HashMap<>();
7+
8+
public boolean isMatch(String s, String p) {
9+
// Check if the result is already computed
10+
String key = s + "," + p;
11+
if (memo.containsKey(key)) {
12+
return memo.get(key);
13+
}
14+
15+
// Base case: if the pattern is empty, the string must also be empty
16+
if (p.isEmpty()) {
17+
return s.isEmpty();
18+
}
19+
20+
// Check if the first characters match
21+
boolean firstMatch = (!s.isEmpty() && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.'));
22+
23+
boolean result;
24+
if (p.length() >= 2 && p.charAt(1) == '*') {
25+
// Handle the '*' case (zero or more occurrences of the preceding character)
26+
result = (isMatch(s, p.substring(2)) || (firstMatch && isMatch(s.substring(1), p)));
27+
} else {
28+
// Handle the normal case (no '*')
29+
result = firstMatch && isMatch(s.substring(1), p.substring(1));
30+
}
31+
32+
// Memoize the result
33+
memo.put(key, result);
34+
return result;
35+
}
36+
}

0 commit comments

Comments
 (0)