Home  >  Article  >  Backend Development  >  An explanation of how to get the first non-repeating character in a character stream in PHP

An explanation of how to get the first non-repeating character in a character stream in PHP

jacklove
jackloveOriginal
2018-07-02 17:55:001792browse

This article mainly introduces the method of PHP to obtain the first non-repeating character in the character stream, involving PHP's operation skills related to traversal and judgment of index arrays. Friends in need can refer to the example of this article

Describes how PHP obtains the first non-repeating character in a character stream. Share it with everyone for your reference. The details are as follows:

Question

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

Solution

Use index Array

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 "#";
}

You may be interested Article:

A brief discussion on the problems often encountered in PHP string reversal interviews

The type declaration of functions in various versions of PHP Detailed explanation

PHP method to implement counting the number of occurrences of a number in a sorted array

The above is the detailed content of An explanation of how to get the first non-repeating character in a character stream in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn