-
Notifications
You must be signed in to change notification settings - Fork 37
/
10 Regular Expression Matching
61 lines (46 loc) · 1.74 KB
/
10 Regular Expression Matching
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
Given an input string (s) and a pattern (p), 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).
Note:
s could be empty and contains only lowercase letters a-z.
p could be empty and contains only lowercase letters a-z, and characters like . or *.
Example 1:
Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
public boolean isMatch(String s, String p) {
boolean[][] dp = new boolean[s.length()+1][p.length()+1];
dp[0][0] = true;
char[] string = new char[s.length()+1];
char[] pattern = new char[p.length()+1];
string[0] = (char)0;
pattern[0] = (char)0;
for(int i=0;i<s.length();i++){
string[i+1] = s.charAt(i);
}
for(int i=0;i<p.length();i++){
pattern[i+1] = p.charAt(i);
}
for(int i=1;i<pattern.length;i++){
if(pattern[i]=='*' && dp[0][i-2]==true){
dp[0][i] = true;
}
}
for(int i=1;i<string.length;i++){
for(int j=1;j<pattern.length;j++){
if(pattern[j]==string[i] || pattern[j]=='.'){
dp[i][j] = dp[i-1][j-1];
}else if(pattern[j]=='*'){
if(pattern[j-1]==string[i] || pattern[j-1]=='.'){
dp[i][j] = dp[i][j-2] || dp[i-1][j];
}else{
dp[i][j] = dp[i][j-2];
}
}
}
}
return dp[s.length()][p.length()];
}