题目:
在字符串中找出第一个只出现一次的字符。
思路:
使用数组模拟哈希表。
代码:
#include <iostream>
using namespace std;
//功能:查找字符串中第一个次数不为1的字符
//先用哈希数组统计一下字符串中每个字符出现的次数,然后再遍历一下,如果次数为1,就直接返回
char FirstNotRepeatingChar(char *pString)
{
if(pString == NULL)
return '\0';
const int tableSize = 256;
unsigned hashTable[tableSize] = {0};
char *p = pString;
while( *p != '\0')
{
hashTable[*p]++;
p++;
}
p = pString;
while(*p != '\0')
{
if(hashTable[*p] == 1)
return *p;
p++;
}
return '\0';
}
int main()
{
char *str = "abcedabcedf";
char a = FirstNotRepeatingChar(str);
cout<<a<<endl;
}