The first non-repeated character in the stream "Sword refers to offer" and the character "Sword refers to offer"
[Disclaimer: All Rights Reserved. indicate the source for reprinting. Do not use it for commercial purposes. Contact mailbox: libin493073668@sina.com]
Question link: http://www.nowcoder.com/practice/00de97733b8e4f97a3fb5c680ee10720? Rp = 3 & ru =/ta/coding-interviews & qru =/ta/coding-interviews/question-ranking
Description
Implement a function to find the first character that appears only once in the livestream. For example, when only the first two characters "go" are read from the sequence stream, the first character that appears only once is "g ". When the first six characters "google" are read from the livestream, the first character that appears only once is "l ".
Output description:
If the current primary Stream does not contain any character once, the # character is returned.
Ideas
We use a hash table to mark the status of each character.
-1: indicates that no
-2: indicates that multiple times have occurred.
0 ~ N: the location where the message appears.
Then we can repeat the loop to find the smallest position.
class Solution{public://Insert one char from stringstreamSolution():index(0){for(int i = 0; i<256; ++i)state[i] = -1;}void Insert(char ch){if(state[ch]==-1)state[ch] = index;else if(state[ch]>=0)state[ch] = -2;++index;}//return the first appearence once char in current stringstreamchar FirstAppearingOnce(){char ch = '#';int minIndex = index;for(int i = 0; i<256; ++i){if(state[i]>=0 && state[i]<minIndex){minIndex = state[i];ch = (char)i;}}return ch;}private:int state[256];int index;};
Copyright Disclaimer: This article is the original article of the blogger. If it is reproduced, please indicate the source