(剑指offer)字符流第一个不重复的字符C++

xiaoxiao2021-02-28  25

题目描述

请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。

在数组、字符串中,与元素是否重复相关的问题,应该要首先想想能不能用哈希表来解决,利用映射关系可以记录不同元素的累加值;这道题就直接用一个哈希数组记录不同字符的数目,然后再遍历整个字符串,看不同元素对应的值是否为1,若为1则返回相应字符,若最后没有找到出现一次的字符,则返回‘#’;

细节见代码:

class Solution { public: string s; int hashTable[256]={0}; //Insert one char from stringstream void Insert(char ch) { if ((int)ch > 256) { return; } s += ch; hashTable[(int)ch]++; } //return the first appearence once char in current stringstream char FirstAppearingOnce() { for (int i = 0; i < s.size(); i++) { if (hashTable[(int)s[i]] == 1) { return s[i]; } } return '#'; } };
转载请注明原文地址: https://www.6miu.com/read-1450212.html

最新回复(0)