forked from yuduozhou/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathRegularExpressionMatching.java
65 lines (54 loc) · 1.77 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Thanks to heartfire.cc
public class Solution {
public boolean isMatch(String s, String p) {
//Java note: s.substring(n) will be "" if n == s.length(), but if n > s.length(), index oob error
// Start typing your Java solution below
// DO NOT write main() function
int i = 0, j = 0;
//you don't have to construct a state machine for this problem
if (s.length() == 0) {
return checkEmpty(p);
}
if (p.length() == 0) {
return false;
}
char c1 = s.charAt(0);
char d1 = p.charAt(0), d2 = '0'; //any init value except '*'for d2 will do
if (p.length()>1){
d2 = p.charAt(1);
}
if (d2 == '*') {
if (compare(c1, d1)) {
//fork here: 1. consume the character, and use the same pattern again.
//2. keep the character, and skip 'd1*' pattern
//Here is also an opportunity to use DP, but the idea is the same
return isMatch(s.substring(1), p) || isMatch(s, p.substring(2));
}
else {
return isMatch(s, p.substring(2));
}
}
else {
if (compare(c1, d1)) {
return isMatch(s.substring(1), p.substring(1));
}
else {
return false;
}
}
}
public boolean compare(char c1, char d1){
return d1 == '.' || c1 == d1;
}
public boolean checkEmpty(String p) {
if (p.length()%2 != 0) {
return false;
}
for (int i = 1; i < p.length(); i+=2) {
if (p.charAt(i) != '*') {
return false;
}
}
return true;
}
}