Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?
- $start = microtime(true);
- function array_key_last($array) {
- if (!is_array($array) || empty($array)) {
- return NULL;
- }
- return array_keys($array)[count($array)-1];
- }
- function checkBraces($string){
- $arrPlus = array(
- '('=>1,
- '['=>2,
- '{'=>3,
- '<'=>4,
- );
- $arrMinus = array(
- ')'=>1,
- ']'=>2,
- '}'=>3,
- '>'=>4,
- );
- $reverseMinus = array(
- ')'=>'(',
- ']'=>'[',
- '}'=>'{',
- '>'=>'<',
- );
- $arPlus = ['(', '[', '{', '<'];
- $arMinus = [')', ']', '}', '>'];
- $strCount = strlen($string);
- $command = array();
- $j = 0;
- $i = 0;
- $curr = $string{1};
- while ($i <= $strCount) {
- $curr = $string{$i};
- if (in_array($curr,$arPlus)) {
- $j+=$arrPlus[$curr];
- $command[] = $curr;
- }
- if (in_array($curr,$arMinus)){
- if ($command){
- if (end($command) !== $reverseMinus[$curr]) return 1;
- if (($delete = end($command) == $reverseMinus[$curr])or end($command) == $curr){
- $j-=$arrMinus[$curr];
- if ($delete){
- unset($command[array_key_last($command)]);
- $delete = 0;
- } else {
- $command[] = $curr;
- }
- }
- } else {
- return 1;
- }
- }
- $i++;
- //var_dump($i);
- }
- return ($j!==0)?1:0;
- }
- echo '<br>Тест #3: ' . checkBraces('before ( middle []) after ') . ' == 0<br>';
- echo '<br>Тест #1: ' . checkBraces('---(++++)----') . ' == 0<br>';
- echo '<br>Тест #2: ' . checkBraces('') . ' -> 0<br>';
- echo '<br>Тест #4: ' . checkBraces(') (') . ' == 1<br>';
- echo '<br>Тест #5: ' . checkBraces('} {') . ' == 1<br>';
- echo '<br>Тест #6: ' . checkBraces('<( >') . ' == 1<br>';
- echo '<br>Тест #7: ' . checkBraces('( [ <> () ] <> )') . ' == 0<br>';
- echo '<br>Тест #8: ' . checkBraces(' ( [)') . ' == 1<br>';
- echo '<br>Тест #9: ' . checkBraces('[)') . ' == 1<br>';
- echo '<br>Тест #10: ' .checkBraces('({)}') . ' == 1<br>';
- echo '<br>Тест #11: ' .checkBraces('({') . ' == 1<br>';
- echo '<br>Время выполнения скрипта: ' . round(microtime(true) - $start, 8) . ' сек.';
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement