forked from ysdeal/LeetJava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathisMatchRegular.java
More file actions
executable file
·46 lines (40 loc) · 1.32 KB
/
isMatchRegular.java
File metadata and controls
executable file
·46 lines (40 loc) · 1.32 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
/*
Implement regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa","aa") true
isMatch("aaa","aa") false
isMatch("aa", "a*") true
isMatch("aa", ".*") true
isMatch("ab", ".*") true
isMatch("aab", "c*a*b") true
*/
import java.util.*;
public class isMatchRegular {
public static void main(String[] args) {
System.out.println(isMatch("aaa","a*"));
}
public static boolean isMatch(String s, String p){
assert(p!=null && (p.length()==0 || p.charAt(0)!='*'));
if(p.length() == 0)
return s.length() == 0;
if(p.length() == 1 || p.charAt(1) != '*'){
if(s.length() < 1 || (p.charAt(0) != '.' && p.charAt(0)!=s.charAt(0)))
return false;
return isMatch(s.substring(1),p.substring(1));
}
else{
int i = -1;
while(i<s.length() && (i<0 || p.charAt(0)=='.' || p.charAt(0)==s.charAt(i))){
if(isMatch(s.substring(i+1),p.substring(2)))
return true;
i++;
}
return false;
}
}
}