-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathletcode-q6.java
More file actions
39 lines (32 loc) · 1.21 KB
/
letcode-q6.java
File metadata and controls
39 lines (32 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
enum MatchResult {
TRUE, FALSE
}
class Solution {
private MatchResult[][] cache;
public boolean isMatch(String s, String p) {
cache = new MatchResult[s.length() + 1][p.length() + 1];
return matchHelper(0, 0, s, p);
}
private boolean matchHelper(int si, int pi, String s, String p) {
if (cache[si][pi] != null) {
return cache[si][pi] == MatchResult.TRUE;
}
boolean matched;
// If we've reached end of pattern, check if string is also fully matched
if (pi == p.length()) {
matched = (si == s.length());
} else {
// Check if current position matches
boolean currentMatch = (si < s.length() &&
(p.charAt(pi) == s.charAt(si) || p.charAt(pi) == '.'));
// Handle '*' wildcard
if (pi + 1 < p.length() && p.charAt(pi + 1) == '*') {
matched = matchHelper(si, pi + 2, s, p) || (currentMatch && matchHelper(si + 1, pi, s, p));
} else {
matched = currentMatch && matchHelper(si + 1, pi + 1, s, p);
}
}
cache[si][pi] = matched ? MatchResult.TRUE : MatchResult.FALSE;
return matched;
}
}