本文實例講述了PHP獲取字符流中第一個不重復字符的方法。分享給大家供大家參考,具體如下:
問題
請實現一個函數用來找出字符流中第一個只出現一次的字符。例如,當從字符流中只讀出前兩個字符”go”時,第一個只出現一次的字符是”g”。當從該字符流中讀出前六個字符“google”時,第一個只出現一次的字符是”l”。
輸出描述:
如果當前字符流沒有存在出現一次的字符,返回#字符
題解
使用索引數組
實現代碼
<?phpglobal $result;//Init module if you needfunction Init(){ global $result; $result = [];}//Insert one char from stringstreamfunction 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 stringstreamfunction FirstAppearingOnce(){ global $result; foreach($result as $k =>$v){ if($v ==1){ return $k; } } return "#";}
希望本文所述對大家PHP程序設計有所幫助。
新聞熱點
疑難解答
圖片精選