-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRegular Expression Matching.cpp
More file actions
106 lines (102 loc) · 2.58 KB
/
Regular Expression Matching.cpp
File metadata and controls
106 lines (102 loc) · 2.58 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
class Solution
{
public:
bool DFS(string s, string p, int s_pos, int p_pos)
{
if(s_pos==s.size()&&p_pos==p.size())
return true;
if(p_pos==p.size())
return false;
if(s_pos==s.size())
{
while(p_pos<p.size()-1&&p[p_pos+1]=='*')
p_pos=p_pos+2;
if(p_pos==p.size())
return true;
else
return false;
}
if(p_pos==p.size()-1||p[p_pos+1]!='*')
{
if(s[s_pos]==p[p_pos]||p[p_pos]=='.')
return DFS(s, p, s_pos+1, p_pos+1);
else
return false;
}
else
{
if(s[s_pos]==p[p_pos]||p[p_pos]=='.')
return DFS(s, p, s_pos, p_pos+2)||DFS(s, p, s_pos+1, p_pos+2)||DFS(s, p, s_pos+1, p_pos);
else
return DFS(s, p, s_pos, p_pos+2);
}
}
bool isMatch(const char *s, const char *p)
{
string ss;
string pp;
int i, length=strlen(s);
while(i<length)
{
ss+=s[i];
i++;
}
i=0, length=strlen(p);
while(i<length)
{
if(i<length-1&&p[i+1]=='*')
{
int j=i+2;
while(j<length-1&&p[i]==p[j]&&p[i+1]==p[j+1])
j+=2;
pp+=p[i];
pp+=p[i+1];
i=j;
}
else
{
pp+=p[i];
i++;
}
}
return DFS(ss, pp, 0, 0);
}
};
class Solution {
public:
bool isMatch(const char *s, const char *p) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(*s == 0)
{
if(*p == 0)
return true;
if(*(p + 1) != '*')
return false;
else
return isMatch(s, p + 2);
}
if(*p == 0)
return false;
if(*(p + 1) == '*')
{
if(isMatch(s, p + 2) == true)
return true;
else if(*p == '.' || *s == *p)
return isMatch(s + 1, p);
else
return false;
}
else if(*p == '.')
{
return isMatch(s + 1, p + 1);
}
else
{
if(*s == *p)
return isMatch(s + 1, p + 1);
else
return false;
}
}
};