-
Notifications
You must be signed in to change notification settings - Fork 4
/
regular-expression-matching.js
69 lines (61 loc) · 1.36 KB
/
regular-expression-matching.js
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
var DEBUG = process.env.DEBUG;
function Reg(char, suffix) {
this.char = char;
this.suffix = suffix;
}
function match(s, r, idxs, idxr) {
if (idxs === s.length && idxr === r.length)
return true;
if (idxr === r.length && idxs !== s.length)
return false;
var result = false;
if (r[idxr].suffix === '*')
result = result || match(s, r, idxs, idxr+1);
if (idxs === s.length) {
return result;
}
if (s[idxs] === r[idxr].char || r[idxr].char === '.') {
if (r[idxr].suffix === '*')
result = result || match(s, r, idxs+1, idxr);
else
result = result || match(s, r, idxs+1, idxr+1);
}
return result;
}
var isMatch = function(s, p) {
var last = null;
var reg = [];
p.split('').forEach(char => {
if (last === null) {
last = char;
} else {
if (char === '*') {
reg.push(new Reg(last, char));
last = null;
} else {
reg.push(new Reg(last));
last = char;
}
}
});
if (last) reg.push(new Reg(last));
return match(s, reg, 0, 0);
};
function test(f) {
[
["aa", "a"],
["aa", "aa"],
["aa", "a*"],
["a", "a*"],
["", "a*"],
["c", "a*"],
["c", ".*"],
["aa", ".*"],
["aab", ".*"],
["aab", "c*a*b"],
["aab", "ca*b"],
].forEach(function (input) {
console.log(f.apply(undefined, input));
});
}
if (DEBUG) test(isMatch);