Balanced Brackets

Balanced Brackets

Hard PHP PHP Control Flow 18 views
Explanation Complexity

Problem Statement

Input is a string with (), [], {}. Print YES if it is balanced, else NO.

Input Format

One line string s.

Output Format

YES or NO.

Example

([{}])
YES

Constraints

|s|

Input / Output Format

Input Format
One line string s.
Output Format
YES or NO.
Constraints
|s|

Examples

Input:
([{}])
Output:
YES

Example Solution (Public)

PHP
<?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';
?>

Official Solution Code

<?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';
?>
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.