Balanced Brackets
PHP
Hard
4 views
Problem Description
Input is a string with (), [], {}. Print YES if it is balanced, else NO.
Input Format
One line string s.
Official Solution
<?php
$inputText=rtrim(stream_get_contents(STDIN));
if($inputText==='') exit;
$st=[];
$ok=true;
for($i=0,$n=strlen($inputText);$i<$n;$i++){
$ch=$inputText[$i];
if($ch==='(' || $ch==='[' || $ch==='{') $st[]=$ch;
elseif($ch===')' || $ch===']' || $ch==='}'){
if(!$st){ $ok=false; break; }
$top=array_pop($st);
if(($ch===')' && $top!=='(') || ($ch===']' && $top!=='[') || ($ch==='}' && $top!=='{')){ $ok=false; break; }
}
}
if($st) $ok=false;
echo $ok ? 'YES' : 'NO';
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!