|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace leetcode; |
|
6
|
|
|
|
|
7
|
|
|
class RegularExpressionMatching |
|
8
|
|
|
{ |
|
9
|
|
|
public static function isMatch(string $s, string $p): bool |
|
10
|
|
|
{ |
|
11
|
|
|
if (empty($s) && empty($p)) { |
|
12
|
|
|
return true; |
|
13
|
|
|
} |
|
14
|
|
|
[$m, $n] = [strlen($s) + 1, strlen($p) + 1]; |
|
15
|
|
|
$dp = array_fill(0, $m, array_fill(0, $n, false)); |
|
16
|
|
|
$dp[0][0] = true; |
|
17
|
|
|
|
|
18
|
|
|
for ($j = 1; $j < $n; $j++) { |
|
19
|
|
|
if ($p[$j - 1] === '*') { |
|
20
|
|
|
$dp[0][$j] = $dp[0][$j - 2]; |
|
21
|
|
|
} |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
|
|
for ($i = 1; $i < $m; $i++) { |
|
25
|
|
|
for ($j = 1; $j < $n; $j++) { |
|
26
|
|
|
if ($p[$j - 1] === '.' || $p[$j - 1] === $s[$i - 1]) { |
|
27
|
|
|
$dp[$i][$j] = $dp[$i - 1][$j - 1]; |
|
28
|
|
|
} elseif ($p[$j - 1] === '*') { |
|
29
|
|
|
$dp[$i][$j] = $dp[$i][$j - 2]; |
|
30
|
|
|
|
|
31
|
|
|
if ($p[$j - 2] === '.' || $p[$j - 2] === $s[$i - 1]) { |
|
32
|
|
|
$dp[$i][$j] |= $dp[$i - 1][$j]; |
|
33
|
|
|
} |
|
34
|
|
|
} else { |
|
35
|
|
|
$dp[$i][$j] = false; |
|
36
|
|
|
} |
|
37
|
|
|
} |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
return (bool) $dp[$m - 1][$n - 1]; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
public static function isMatch2(string $s, string $p): bool |
|
44
|
|
|
{ |
|
45
|
|
|
if (empty($s) && empty($p)) { |
|
46
|
|
|
return true; |
|
47
|
|
|
} |
|
48
|
|
|
[$m, $n] = [strlen($s) + 1, strlen($p) + 1]; |
|
49
|
|
|
$dp = array_fill(0, $m, array_fill(0, $n, false)); |
|
50
|
|
|
$dp[0][0] = true; // since empty string matches empty pattern |
|
51
|
|
|
for ($j = 2; $j < $n; $j += 2) { |
|
52
|
|
|
if ($p[$j - 1] === '*' && $dp[0][$j - 2]) { |
|
53
|
|
|
$dp[0][$j] = true; |
|
54
|
|
|
} |
|
55
|
|
|
} |
|
56
|
|
|
for ($i = 1; $i < $m; $i++) { |
|
57
|
|
|
for ($j = 1; $j < $n; $j++) { |
|
58
|
|
|
if ($s[$i - 1] === $p[$j - 1] || $p[$j - 1] === '.') { |
|
59
|
|
|
$dp[$i][$j] = $dp[$i - 1][$j - 1]; |
|
60
|
|
|
} |
|
61
|
|
|
if ($p[$j - 1] === '*') { |
|
62
|
|
|
if ($p[$j - 2] !== '.' && $p[$j - 2] !== $s[$i - 1]) { |
|
63
|
|
|
$dp[$i][$j] = $dp[$i][$j - 2]; |
|
64
|
|
|
} else { |
|
65
|
|
|
$dp[$i][$j] = ($dp[$i][$j - 2] || $dp[$i - 1][$j - 2] || $dp[$i - 1][$j]); |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
return (bool) $dp[$m - 1][$n - 1]; |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
|