Created
October 3, 2018 01:58
-
-
Save DimkaJack/79a60d50ce3d461134e52e4d9e6c6625 to your computer and use it in GitHub Desktop.
Проверка на парные скобки
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 | |
/** | |
* Проверка на парные скобки | |
* | |
* @param $string | |
* @return int | |
*/ | |
function checkBraces($string) | |
{ | |
$braces_list = [ | |
'(' => ')', | |
'{' => '}', | |
'[' => ']', | |
'<' => '>', | |
]; | |
//Вытаскиваем все скобки из строки | |
preg_match_all('/[\(\)\{\}\[\]\<\>]/', $string, $braces_array); | |
$braces_array = $braces_array[0]; | |
//Если первая скоба открывающая | |
if (in_array($braces_array[0], $braces_list)) { | |
return 0; | |
} | |
$i = 0; | |
while (true) { | |
$count_braces = count($braces_array); | |
//Если отсутствуют скобки | |
if ($count_braces <= 0) { | |
return 1; | |
} | |
//Если скобок нечетное кол-во | |
if ($count_braces % 2 != 0) { | |
return 0; | |
} | |
//Если скобка закрывающая | |
if (in_array($braces_array[$i], $braces_list)) { | |
//Если предыдущая скобка парная | |
if ($braces_array[$i - 1] == array_flip($braces_list)[$braces_array[$i]]) { | |
//Удаляем пару, откатываем счетчик | |
$i--; | |
array_splice($braces_array, $i, 2); | |
continue; | |
} else { | |
return 0; | |
} | |
} | |
//Если перебрали массив | |
if ($i > $count_braces) { | |
return 0; | |
} | |
$i++; | |
} | |
return 0; | |
} | |
//Тест | |
$time_start = microtime(true); | |
for($i=0; $i<1; $i++){ | |
echo checkBraces("---(++++)----"); | |
echo checkBraces(""); | |
echo checkBraces("before ( middle []) after "); | |
echo checkBraces(") ("); | |
echo checkBraces("} {"); | |
echo checkBraces("<( >)"); | |
echo checkBraces("( [ <> () ] <> )"); | |
echo checkBraces(" ( [)"); | |
//11100010 | |
} | |
$time_end = microtime(true); | |
$execution_time = ($time_end - $time_start)/60; | |
echo '<br/><br/><b>Затраченно:</b> '.$execution_time.' мин.'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment