fork download
  1. <?php
  2. function isValidBraces($line) {
  3. if (!is_string($line)) {
  4. throw new InvalidArgumentException("Input must be stirng.");
  5. }
  6.  
  7. $braces = array(
  8. array('[', ']'),
  9. array('{', '}'),
  10. array('(', ')')
  11. );
  12. $counters = array_fill(0, count($braces), 0);
  13.  
  14. foreach (str_split($line) as $char) {
  15. echo $char . "\r\n";
  16. for ($i = 0; $i < count($braces); $i++) {
  17. $counters[$i] += $char == $braces[$i][0];
  18. $counters[$i] -= $char == $braces[$i][1];
  19. // closing braces should not be first
  20. if ($counters[$i] < 0) {
  21. return false;
  22. }
  23. }
  24. }
  25.  
  26. print_r($counters);
  27. foreach ($counters as $counter) {
  28. // number of onpening and closing braces should be the same
  29. if ($counter > 0)
  30. return false;
  31. }
  32.  
  33. return true;
  34. }
  35.  
  36. echo isValidBraces('[(])') . "\r\n";
  37. ?>
Success #stdin #stdout 0.01s 20568KB
stdin
Standard input is empty
stdout
[
(
]
)
Array
(
    [0] => 0
    [1] => 0
    [2] => 0
)
1