Playlist Manager
PHP
Medium
7 views
Problem Description
Build a Playlist object and process commands: ADD song, REMOVE song, COUNT. Songs are unique by name. COUNT prints how many songs are in the playlist.
Input Format
First line q. Next q lines commands.
Output Format
Outputs for COUNT.
Sample Test Case
Input:
8
COUNT
ADD song1
ADD song2
COUNT
ADD song1
REMOVE song2
COUNT
REMOVE song3
Official Solution
<?php
class Playlist{
private $songs=[];
function addSong($song){ $this->songs[$song]=true; }
function removeSong($song){ unset($this->songs[$song]); }
function size(){ return count($this->songs); }
}
$inputLines=preg_split('/\\R/', rtrim(stream_get_contents(STDIN)));
if(!$inputLines || trim($inputLines[0])==='') exit;
$q=intval($inputLines[0]);
$playlist=new Playlist();
$output=[];
for($lineNo=1;$lineNo<=$q;$lineNo++){
$line=trim($inputLines[$lineNo] ?? '');
if($line==='') continue;
$parts=preg_split('/\\s+/', $line, 2);
$cmd=$parts[0] ?? '';
$song=$parts[1] ?? '';
if($cmd==='ADD') $playlist->addSong($song);
elseif($cmd==='REMOVE') $playlist->removeSong($song);
else $output[] = strval($playlist->size());
}
echo implode(PHP_EOL,$output);
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!