-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathMinimumWindowSubstring.php
84 lines (78 loc) · 2.29 KB
/
MinimumWindowSubstring.php
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
<?php
declare(strict_types=1);
namespace leetcode;
class MinimumWindowSubstring
{
public static function minWindow(string $s, string $t): string
{
[$m, $n, $map, $win] = [strlen($s), strlen($t), [], []];
if ($m === 0 || $n === 0) {
return '';
}
for ($i = 0; $i < $n; $i++) {
$k = $t[$i];
$map[$k] = ($map[$k] ?? 0) + 1;
}
$left = $right = $match = $start = 0;
$len = PHP_INT_MAX;
while ($right < $m) {
$c = $s[$right];
$right++;
if (isset($map[$c])) {
$win[$c] = ($win[$c] ?? 0) + 1;
if ($win[$c] === $map[$c]) {
$match++;
}
}
while ($match === count($map)) {
if ($right - $left < $len) {
$start = $left;
$len = $right - $left;
}
$d = $s[$left];
$left++;
if (isset($map[$d])) {
if ($win[$d] === $map[$d]) {
$match--;
}
$win[$d]--;
}
}
}
return $len === PHP_INT_MAX ? '' : substr($s, $start, $len);
}
public static function minWindow2(string $s, string $t): string
{
[$m, $n, $map] = [strlen($s), strlen($t), []];
if ($m === 0 || $n === 0) {
return '';
}
for ($i = 0; $i < $n; $i++) {
$k = $t[$i];
$map[$k] = ($map[$k] ?? 0) + 1;
}
$left = $right = $start = 0;
$len = PHP_INT_MAX;
while ($right < $m) {
$c = $s[$right];
$right++;
if (isset($map[$c]) && $map[$c] > 0) {
$n--;
}
$map[$c] = ($map[$c] ?? 0) - 1;
while ($n === 0) {
if ($right - $left < $len) {
$len = $right - $left;
$start = $left;
}
$d = $s[$left];
$left++;
$map[$d] = ($map[$d] ?? 0) + 1;
if ($map[$d] > 0) {
$n++;
}
}
}
return $len === PHP_INT_MAX ? '' : substr($s, $start, $len);
}
}