-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRegexMatch.java
More file actions
56 lines (50 loc) · 1.21 KB
/
RegexMatch.java
File metadata and controls
56 lines (50 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package codingInterview;
public class RegexMatch {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "a";
String pat = ".*";
boolean isMatch = isMatch(str, pat);
System.out.println(isMatch);
}
// classify the cases
private static boolean isMatch(String str, String pat) {
// TODO Auto-generated method stub
// base case
if (pat.length() == 0) {
return str.length() == 0;
}
// special case
if (pat.length() == 1) {
if (str.length() < 1) {
return false;
} else if (str.charAt(0) != pat.charAt(0) && pat.charAt(0) != '.') {
return false;
} else {
return isMatch(str.substring(1), pat.substring(1));
}
}
if (pat.charAt(1) != '*') {
if (str.length() < 1) {
return false;
} else if (str.charAt(0) != pat.charAt(0) && pat.charAt(0) != '.') {
return false;
} else {
return isMatch(str.substring(1), pat.substring(1));
}
} else {
if (isMatch(str, pat.substring(2))) {
return true;
}
int i = 0;
while (i < str.length()
&& (str.charAt(i) == pat.charAt(0) || pat.charAt(0) == '.')) {
if (isMatch(str.substring(i + 1), pat.substring(2))) {
return true;
}
i++;
}
return false;
}
}
}