The first occurrence of only one character, the first occurrence of a character
Question: Find the first character that appears only once in the string. If "abaccdeff" is input, 'B' is output '.
Thought 1: traverse, that is, take a character in the string from the beginning and compare it with all subsequent characters. If there are the same characters, then it is proved that it does not appear only once. When the characters after the traversal are not repeated for the first time, it indicates that the character is "the first character that appears only once ".
Idea 2: we can define that the Key Value (Key) of the hash table is the ASCII Value of the character, and the Value is the number of times that the character appears. At the same time, we need to scan the string twice. When scanning the string for the first time, the number of times is increased by 1 in the corresponding items of the hash table for each scanned character. During the second scan, the number of times that character appears in the hash table is displayed without scanning a character. Find the key whose first Value is 1, which is the character we need to find.
1 #include <string> 2 #include "stdafx.h" 3 4 char FirstNotRepeatingChar(char* pString) 5 { 6 if(pString == NULL) 7 return '\0'; 8 9 const int tableSize = 256;10 unsigned int hashTable[tableSize];11 for(unsigned int i = 0;i < tableSize ; ++i)12 hashTable[i] = 0;13 14 char* pHashKey = pString;15 while(*pHashKey != '\0')16 hashTable[*(pHashKey++)] ++;17 18 pHashKey = pString;19 while(*pHashKey != '\0')20 {21 if(hashTable[*pHashKey] == 1)22 return *pHashKey;23 24 pHashKey ++ ;25 }26 27 return '\0';28 }29 30 31 int main()32 {33 34 char* pString = "google";35 printf("%c\n", FirstNotRepeatingChar(pString));36 37 pString = "abcdefg";38 printf("%c\n", FirstNotRepeatingChar(pString));39 40 return 0;41 }