PHP Method for getting the first non repeating character in a character stream

  • 2021-09-04 23:39:31
  • OfStack

In this paper, an example is given to describe the method of obtaining the first non-repeating character in PHP character stream. Share it for your reference, as follows:

Problem

Please implement a function to find the first character in the character stream that appears only once. For example, when only the first two characters "go" are read from the character stream, the first character appearing only once is "g". When the first six characters "google" are read from the character stream, the first character appearing only once is "l".
Output description:
Returns the # character if there is no character occurring once in the current character stream

Problem solution

Using indexed arrays

Implementation code


<?php
global $result;
//Init module if you need
function Init(){
  global $result;
  $result = [];
}
//Insert one char from stringstream
function Insert($ch)
{
  global $result;
  // write code here
  if(isset($result[$ch])){
    $result[$ch]++;
  }else{
    $result[$ch] =1; 
  }
}
//return the first appearence once char in current stringstream
function FirstAppearingOnce()
{
  global $result;
  foreach($result as $k =>$v){
    if($v ==1){
      return $k;
    }
  }
  return "#";
}

More readers interested in PHP can check the topics of this site: "PHP Data Structure and Algorithm Tutorial", "php Programming Algorithm Summary", "php String (string) Usage Summary", "PHP Array (Array) Operation Skills Complete Book", "PHP Common Traversal Algorithms and Skills Summary" and "PHP Mathematical Operation Skills Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: