
function minWindow($s, $t) {
$_tCount = array_count_values(str_split($t));
$_tN = count($_tCount);
$_sLen = strlen($s);
$_winCount = [];
$valid = 0;
$ansL = 0;
$l = 0;
$r = 0;
$ansMinLen = PHP_INT_MAX;
while ($r<$_sLen) {
$char = $s[$r];
if (array_key_exists($char, $_tCount)) {
$_winCount[$char] = isset($_winCount[$char]) ? ++$_winCount[$char] : 1;
if ($_winCount[$char] == $_tCount[$char]) {
$valid++;
}
}
while ($valid == $_tN && $l <= $r) {
if ($r-$l+1 < $ansMinLen) {
$ansMinLen = $r-$l+1;
$ansL = $l;
}
if (array_key_exists($s[$l], $_winCount)) {
$_winCount[$s[$l]]--;
if ($_winCount[$s[$l]] < $_tCount[$s[$l]]) {
$valid--;
}
}
$l++;
}
$r++;
}
return $ansMinLen == PHP_INT_MAX ? '' : substr($s, $ansL, $ansMinLen);
}
|