-
Notifications
You must be signed in to change notification settings - Fork 692
/
RegularExpression.java
84 lines (61 loc) · 2.39 KB
/
RegularExpression.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package strings;
public class RegularExpression {
/*
* Given a text and a pattern, determine if the pattern matches with text completely or not using regular
* expression matching. For simplicity assume that the pattern may contain only two operators i.e. '.' and '*'.
* Operator '*' in pattern means that the character preceding '*' may not appear or may appear any number of times
* in text. Operator '.' matches with any character in text exactly once.
* */
/*
* Runtime Complexity - Exponential
* Memory Complexity - Exponential
* */
public static boolean isRegexMatch(String text, String pattern) {
if (text.isEmpty() && pattern.isEmpty()) {
return true;
}
if (!text.isEmpty() && pattern.isEmpty()) {
return false;
}
if (pattern.length() > 1 && pattern.charAt(1) == '*') {
String remainingPattern = pattern.substring(2);
String remainingText = text;
for (int i = 0; i < text.length() + 1; ++i) {
if (isRegexMatch(remainingText, remainingPattern)) {
return true;
}
if (remainingText.isEmpty()) {
return false;
}
if (pattern.charAt(0) != '.' && remainingText.charAt(0) != pattern.charAt(0)) {
return false;
}
remainingText = remainingText.substring(1);
}
}
if(text.isEmpty() || pattern.isEmpty()) {
return false;
}
if(pattern.charAt(0) == '.' || pattern.charAt(0) == text.charAt(0)) {
String remainingText = "";
if (text.length() >= 2) {
remainingText = text.substring(1);
}
String remainingPattern = "";
if (pattern.length() >= 2) {
remainingPattern = pattern.substring(1);
}
return isRegexMatch(remainingText, remainingPattern);
}
return false;
}
static boolean regexMatch(String text, String pattern) {
return isRegexMatch(text, pattern);
}
public static void main(String[] args) {
String input = "aabbbbbcdda";
String pattern = "a*bb*cdda"; // -> true
// String pattern = "a*b*c*da"; // -> false
System.out.println(regexMatch(input, pattern));
}
}