有两种方法,第一种利用哈希表
由于字符char是一个长度为8的数据类型,总共有256中可能,于是我们创建一个长度为256的数组,每个字母根据其ASCII码值作为数组的下标对应于数组的对应项,数组中存放的的是每个字符出现的次数,这样我们就建立了一个大小为256,键值为ASCII码的哈希表。程序如下:
注意:容易在第二次循环时忘记再次给PHashKey赋值,使其指向字符串的开始,否则无输出值。
#include <iostream>
using namespace std;
char FirstNotRepeatingChar(char* pString)
{
if(!pString)
return 0;
const int tableSize=256;
unsigned int hashTable[tableSize];
for(unsigned int i=0;i<tableSize;++i)
{hashTable[i]=0;
}
char* pHashKey=pString;
while(*(pHashKey)!='\0')
{
hashTable[*(pHashKey++)]++;
}
pHashKey=pString;//at first I forget initialize the pHashKey again!
while(*(pHashKey)!='\0')
{
if(hashTable[*pHashKey]==1)
return *pHashKey;
pHashKey++;
}
return 0;
}
void main()
{
char a[]="abcfabcd";
char result=FirstNotRepeatingChar(a);
cout<<result<<endl;
}
第二种方法:
#include <iostream>
using namespace std;
char FirstSingleChar(char* pstr)
{
const int tableSize=256;
unsigned int a[tableSize];
//unsigned int a[256];
//for(unsigned int i=0;i<=255;i++)
for(unsigned int i=0;i<tableSize;++i)
a[i]=0;
char *p=pstr;
while(*p!='\0')
{
a[*p]++;
p++;
}
p=pstr;
while(*p!='\0')
{
if(a[*p]==1)
return *p;
p++;
}
return 0;
}
void main()
{
char s[]="abcdabc";
//char *q=s;
//cout<<a;
char result=FirstSingleChar(s);
cout<<result<<endl;
}