-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathT10_Regular_Expression_matching.java
More file actions
63 lines (51 loc) · 1.72 KB
/
T10_Regular_Expression_matching.java
File metadata and controls
63 lines (51 loc) · 1.72 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
//c++ reference.
/*
class Solution {
public:
bool matchFirst(const char *s, const char *p){
return (*p == *s || (*p == '.' && *s != '\0'));
}
bool isMatch(const char *s, const char *p) {
if (*p == '\0') return *s == '\0'; //empty
if (*(p + 1) != '*') {//without *
if(!matchFirst(s,p)) return false;
return isMatch(s + 1, p + 1);
} else { //next: with a *
if(isMatch(s, p + 2)) return true; //try the length of 0
while ( matchFirst(s,p) ) //try all possible lengths
if (isMatch(++s, p + 2))return true;
}
}
};
*/
public class T10 {
static boolean matchFirst(String s, String p){
System.out.println("in matchFirst: s is "+s+",p is: "+p+";");
System.out.println("s is empty "+ s.isEmpty());
System.out.println("p is empty "+ p.isEmpty());
if(s.isEmpty() ^ p.isEmpty()) return false;
if(s.isEmpty() && p.isEmpty()) return true;
return ( s.charAt(0)==p.charAt(0) || p.charAt(0)=='.' );
}
public static boolean isMatch(String s, String p) {
if (p.isEmpty() )return (s.isEmpty());
if(p.length()==1 || p.charAt(1)!='*') {
if(!matchFirst(s,p)) return false;
return isMatch(s.substring(1), p.substring(1));
} else {
if (isMatch(s, p.substring(2))) return true;
while(true){
if(isMatch(s, p.substring(2))) return true;
if(!matchFirst(s, p)) break;
s=s.substring(1);
}
}
return false;
}
public static void main(String[] args){
String s = "aaa";
String p = "ab*a";
boolean ret = isMatch(s, p);
System.out.println(ret);
}
}