Mini Scope Interpreter
PHP
Hard
6 views
Problem Description
Commands: BEGIN, END, SET name value, GET name. GET searches inner to outer. Print value or NOT_FOUND.
Input Format
First line q. Next q lines.
Output Format
Outputs for GET.
Sample Test Case
Input:
9
SET a 1
BEGIN
GET a
SET a 2
GET a
END
GET a
GET b
END
Official Solution
<?php
$inputLines=preg_split('/\\R/', trim(stream_get_contents(STDIN)));
if(!$inputLines || trim($inputLines[0])==='') exit;
$q=intval($inputLines[0]);
$stack=[[]];
$output=[];
for($i=1;$i<=$q;$i++){
$tokens=preg_split('/\\s+/', trim($inputLines[$i] ?? ''), 3);
if(!$tokens[0]) continue;
$cmd=$tokens[0];
if($cmd==='BEGIN'){ $stack[]=[]; continue; }
if($cmd==='END'){ if(count($stack)>1) array_pop($stack); continue; }
if($cmd==='SET'){ $stack[count($stack)-1][$tokens[1] ?? '']=$tokens[2] ?? ''; continue; }
$name=$tokens[1] ?? '';
$val=null;
for($s=count($stack)-1;$s>=0;$s--){
if(array_key_exists($name,$stack[$s])){ $val=$stack[$s][$name]; break; }
}
$output[] = ($val===null?'NOT_FOUND':$val);
}
echo implode(PHP_EOL,$output);
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!