思路1:遍歷,也就是從頭開始取字符串中的一個字符,將其與其後的所有字符比較,如果有相同的字符,那麼就證明它不是只出現一次的字符。當第一次出現遍歷完其後字符並且沒有重復時,表明這個字符就是“第一個只出現一次的字符”。
思路2:我們可以定義哈希表的鍵值(Key)是字符的ASCII值,而值(Value)是該字符出現的次數。同時我們需要掃描兩次字符串,第一次掃描字符串時,每掃描到一個字符就在哈希表的對應項中把次數加1。接下來第二次掃描的時候,沒掃描到一個字符就能在哈希表中得到該字符出現的次數。找出第一個Value為1的那個key就是我們需要找到那個字符。
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 }
