Created
January 21, 2021 21:11
-
-
Save lyquocphong/f1297463852d5fce675496f7be3ed743 to your computer and use it in GitHub Desktop.
Minimum window substring
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$str = 'abbaacdbcab'; | |
$chars = ['a', 'b', 'c']; | |
echo "Expected: bca | Result: ".findMinWinSubString($str, $chars)."\n"; | |
$str = 'xyyzyzyx'; | |
$chars = ['x', 'y', 'z']; | |
echo "Expected: xyz | Result: ".findMinWinSubString($str, $chars)."\n"; | |
function findMinWinSubString($str, $chars) { | |
$right = 0; | |
$left = 0; | |
$checkWindow = []; | |
$uniqueCounter = 0; | |
$requiredCounter = count($chars); | |
foreach($chars as $char) { | |
if (!isset($checkWindow[$char])) { | |
$checkWindow[$char] = 0; | |
} | |
$checkWindow[$char] += 1; | |
} | |
$minWindow = []; | |
while ($right < strlen($str)) { | |
$char = $str[$right]; | |
if (!isset($minWindow[$char])) { | |
$minWindow[$char] = 0; | |
} | |
if (in_array($char, $chars) && $minWindow[$char] == 0) { | |
$uniqueCounter += 1; | |
} | |
$minWindow[$char] += 1; | |
while ($uniqueCounter == $requiredCounter) { | |
$length = $right - $left + 1; | |
if ($length === $uniqueCounter && $uniqueCounter == $requiredCounter) { | |
return substr($str, $left, $length); | |
} | |
$headChar = $str[$left]; | |
$minWindow[$headChar] -= 1; | |
if ($minWindow[$headChar] == 0 && in_array($headChar, $chars)) { | |
$uniqueCounter -= 1; | |
} | |
$left += 1; | |
} | |
$right += 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment