First Non-Repeating Character
PHP
Medium
4 views
Problem Description
Print the first character that appears only once. If none, print -1.
Input Format
One line string s.
Output Format
One character or -1.
Official Solution
<?php
$inputText=rtrim(stream_get_contents(STDIN));
if($inputText==='') exit;
$freq=[];
for($i=0,$n=strlen($inputText);$i<$n;$i++){
$ch=$inputText[$i];
if(!isset($freq[$ch])) $freq[$ch]=0;
$freq[$ch]++;
}
$ans='-1';
for($i=0,$n=strlen($inputText);$i<$n;$i++) if(($freq[$inputText[$i]] ?? 0)===1){ $ans=$inputText[$i]; break; }
echo $ans;
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!