The first non-repeated character in the stream "Sword refers to offer" and the character "Sword refers to offer"

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.