-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopen-bracket-counter.php
35 lines (26 loc) · 1021 Bytes
/
open-bracket-counter.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
<?php
require_once 'structures/stack.php';
function analyzeBracket(string $s): string
{
$stack = new Stack();
$openBrackets = ['(', '[', '{'];
for ($i = 0; $i < strlen($s); $i++) {
if (in_array($s[$i], $openBrackets)) {
$stack->push($s[$i]);
continue;
}
$closeIndex = array_search($s[$i], [')', ']', '}']);
if ($closeIndex !== false && ($stack->isEmpty() || $stack->pop() !== $openBrackets[$closeIndex])) {
return 'Brackets is broken!';
}
}
return $stack->isEmpty() ? 'Brackets is fine!' : 'Brackets is broken!';
}
$result = analyzeBracket('(1+2*3*(1+2)+1)');
var_dump($result, $result === 'Brackets is fine!');
$result = analyzeBracket('(1+2*3*{(1+2)}+1)');
var_dump($result, $result === 'Brackets is fine!');
$result = analyzeBracket('(1+2*3*((1+2)+1)');
var_dump($result, $result === 'Brackets is broken!');
$result = analyzeBracket('(1+2*3*((1+2)))+1)');
var_dump($result, $result === 'Brackets is broken!');