在字符串中找出第一个只出现一次的字符。如输入”abaccdeff”,则输出’b’。
我们可以定义一个哈希表,键值是字符,而值是该字符出现的次数。同时我们还需要从头开始扫描字符串两次。第一次扫描字符串时,每扫描到一个字符就在哈希表的对应项中把次数加1.接下来第二次扫描时,每扫描到一个字符就能从哈希表中得到该字符出现的次数。这样第一个值出现一次的字符就是符合该要求的输出。
#include <iostream>
using namespace std;
char FirstNotRepaetingchar(char *pString)
{
if(pString == NULL)
return '\0';
int tablesize = 256;
unsigned int hashtable[tablesize];
for(unsigned i = 0; i < tablesize; ++i)
hashtable[i] = 0;
char *key = pString;
while(*key != '\0')
hashtable[*key++]++;
key = pString;
while(*key != '\0')
{
if(hashtable[*key] == 1)
return *key;
++key;
}
return '\0';
}
int main()
{
char *String = "aabbdceef";
cout<<"first Number:"<<FirstNotRepaetingchar(String)<<endl;
}