Undoable Text Editor

Undoable Text Editor

Hard PHP PHP OOP Basics 34 views
Explanation Complexity

Problem Statement

Commands: ADD text, DEL k, UNDO. Print final text.

Input Format

First line q. Next q lines.

Output Format

One line final text.

Example

6
ADD ab
ADD cd
DEL 1
UNDO
ADD e
UNDO
abcd

Constraints

q

Input / Output Format

Input Format
First line q. Next q lines.
Output Format
One line final text.
Constraints
q

Examples

Input:
6 ADD ab ADD cd DEL 1 UNDO ADD e UNDO
Output:
abcd

Example Solution (Public)

PHP
<?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();
?>

Official Solution Code

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

                                        
Please login to submit solutions.