forked from rpj911/LeetCode_algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIsMach.java
More file actions
70 lines (57 loc) · 2.25 KB
/
IsMach.java
File metadata and controls
70 lines (57 loc) · 2.25 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
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
66
67
68
69
70
package Algorithms.algorithm.others;
public class IsMach {
public static void main(String[] str) {
//System.out.println(isMatch("aa", "aa"));
System.out.println(isMatch("aab", "c*a*b"));
}
public static boolean isMatch(String s, String p) {
if (s == null || p == null) {
return false;
}
return help(s, p, 0, 0);
}
public static boolean help(String s, String p, int indexS, int indexP) {
int pLen = p.length();
int sLen = s.length();
// 1. P?????????????????? S??????????????????
if (indexP == pLen) {
return indexS == sLen;
}
// 2. P ??????????????????????????????
if (indexP == pLen - 1) {
// ????????????????????????p???'.'.
// S????????????????????????
return indexS == sLen - 1 && matchChar(s, p, indexS, indexP);
}
// ??????P ????????????2?????????.
// 2. ?????????????????????, ??? aa, a. ????????????
if (p.charAt(indexP + 1) != '*') {
if (indexS < sLen && matchChar(s, p, indexS, indexP)) {
return help(s, p, indexS + 1, indexP + 1); // p??????????????????
} else {
return false;
}
}
// 3. ?????????????????????, ??? .* or a* ,????????????????????????
// ??????????????????2??????????????????????????????????????????
if (help(s, p, indexS, indexP + 2)) {
return true;
}
// ?????????????????????,?????????????????????p????????? ??????1???????????????
for (int i = indexS; i < sLen; i++) {
if (!matchChar(s, p, i, indexP)) {
return false;
} else {
if (help(s, p, i + 1, indexP + 2)) {
return true;
}
}
}
// ??????????????????????????????????????????????????????????????????????????????
return false;
}
// check if the s match p in the index.
public static boolean matchChar(String s, String p, int indexS, int indexP) {
return (s.charAt(indexS) == p.charAt(indexP)) || p.charAt(indexP) == '.';
}
}