Undoable Text Editor
PHP
Hard
6 views
Problem Description
Commands: ADD text, DEL k, UNDO. Print final text.
Input Format
First line q. Next q lines.
Output Format
One line final text.
Sample Test Case
Input:
6
ADD ab
ADD cd
DEL 1
UNDO
ADD e
UNDO
Official Solution
<?php
class Editor{
private $s='';
private $hist=[];
function add($t){ $this->hist[]=$this->s; $this->s.=$t; }
function del($k){ $this->hist[]=$this->s; $this->s=substr($this->s,0,max(0,strlen($this->s)-$k)); }
function undo(){ if($this->hist) $this->s=array_pop($this->hist); }
function text(){ return $this->s; }
}
$inputLines=preg_split('/\\R/', rtrim(stream_get_contents(STDIN)));
if(!$inputLines || trim($inputLines[0])==='') exit;
$q=intval($inputLines[0]);
$ed=new Editor();
for($i=1;$i<=$q;$i++){
$t=trim($inputLines[$i] ?? '');
if($t==='') continue;
if(strpos($t,'ADD')===0){ $tokens=preg_split('/\\s+/', $t, 2); $ed->add($tokens[1] ?? ''); }
elseif(strpos($t,'DEL')===0){ $tokens=preg_split('/\\s+/', $t, 2); $ed->del(intval($tokens[1] ?? 0)); }
else $ed->undo();
}
echo $ed->text();
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!