Prove safety offer 54. The first string in the character stream not repeated character

Title Description

Please implement a function to find the character stream for the first time a character appears only. For example, when the character stream reads only the first two characters "go", the first character only occurs once a "g". When reading out the first six characters "google" from the character stream, first appears only one character is "l".

Output Description

If the current character stream does not appear there is a character, returns the # character.

Problem-solving ideas

A character accounted for 8, and therefore will not be more than 256, 256 can apply a size of the array to achieve a simple hash table. The time complexity is O (n), the spatial complexity of O (n).

code show as below

            int[] hashtable=new int[256];
            StringBuffer s=new StringBuffer();
            //Insert one char from stringstream
            public void Insert(char ch)
            {
                s.append(ch);
                if(hashtable[ch]==0)
                    hashtable[ch]=1;
                else hashtable[ch]+=1;
            }
          //return the first appearence once char in current stringstream
            public char FirstAppearingOnce()
            {
              char[] str=s.toString().toCharArray();
              for(char c:str)
              {
                  if(hashtable[c]==1)
                      return c;
              }
              return '#';
            }

 

Guess you like

Origin www.cnblogs.com/Transkai/p/11407602.html