forked from LeetCode-in-Php/LeetCode-in-Php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.php
41 lines (38 loc) · 1.19 KB
/
Solution.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
<?php
namespace leetcode\g0001_0100\s0076_minimum_window_substring;
// #Hard #Top_100_Liked_Questions #Top_Interview_Questions #String #Hash_Table #Sliding_Window
// #Level_2_Day_14_Sliding_Window/Two_Pointer #Big_O_Time_O(s.length())_Space_O(1)
// #2023_12_10_Time_21_ms_(100.00%)_Space_19.5_MB_(89.09%)
class Solution {
/**
* @param String $s
* @param String $t
* @return String
*/
public function minWindow($s, $t) {
$map = array_fill(0, 128, 0);
for ($i = 0; $i < strlen($t); $i++) {
$map[ord($t[$i]) - ord('A')]++;
}
$count = strlen($t);
$begin = 0;
$end = 0;
$d = PHP_INT_MAX;
$head = 0;
while ($end < strlen($s)) {
if ($map[ord($s[$end++]) - ord('A')]-- > 0) {
$count--;
}
while ($count == 0) {
if ($end - $begin < $d) {
$d = $end - $begin;
$head = $begin;
}
if ($map[ord($s[$begin++]) - ord('A')]++ == 0) {
$count++;
}
}
}
return $d == PHP_INT_MAX ? "" : substr($s, $head, $head + $d);
}
}