forked from Gaurang2908/HacktoberFest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathregularexpressionmatching.java
31 lines (31 loc) · 1.16 KB
/
regularexpressionmatching.java
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
public class Solution {
public boolean isMatch(String s, String p) {
if(s == null || p == null) {
return false;
}
boolean[][] state = new boolean[s.length() + 1][p.length() + 1];
state[0][0] = true;
for (int j = 1; j < state[0].length; j++) {
if (p.charAt(j - 1) == '*') {
if (state[0][j - 1] || (j > 1 && state[0][j - 2])) {
state[0][j] = true;
}
}
}
for (int i = 1; i < state.length; i++) {
for (int j = 1; j < state[0].length; j++) {
if (s.charAt(i - 1) == p.charAt(j - 1) || p.charAt(j - 1) == '.') {
state[i][j] = state[i - 1][j - 1];
}
if (p.charAt(j - 1) == '*') {
if (s.charAt(i - 1) != p.charAt(j - 2) && p.charAt(j - 2) != '.') {
state[i][j] = state[i][j - 2];
} else {
state[i][j] = state[i - 1][j] || state[i][j - 1] || state[i][j - 2];
}
}
}
}
return state[s.length()][p.length()];
}
}