How to get the first non-repeating character in the character stream in PHP

jacklove
Release: 2023-03-27 14:44:02
Original
1746 people have browsed it

This article explains how PHP obtains the first non-repeating character in the character stream.

Please implement a function to find the first character that appears only once in the character stream. 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 the index array

Implementation code

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

This article explains how PHP obtains the first non-repeating character in the character stream. For more related content, please pay attention to the php Chinese website.

Related recommendations:

PHP uses one line of code to delete all files in a directory

PHP implements clockwise printing of matrix and Spiral matrix method

PHP method to determine whether a binary tree is symmetrical


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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template