思路:用数组模拟哈希表,保存字符和其出现次数的映射关系,然后从头开始扫描字符串即可求解
代码如下:
#include "stdafx.h" #include <iostream> using namespace std; //从字符串中找到第一个只出现一次的字符 char FirstNotRepeatChar(char *Str) { if (Str == NULL) { return NULL; } //用数组模拟哈希表 int HashTable[256] = {0}; char *pCur = Str; char cResult = '#'; while ( *pCur != '' ) { HashTable[*pCur++]++; } pCur = Str;//重新指回字符串的首字符 while (*pCur != '') { if (HashTable[*pCur] == 1) { cResult = *pCur; break; } pCur++; } if (cResult == '#') { cout << "不存在只出现一次的字符!" << endl; } return cResult; } int _tmain(int argc, _TCHAR* argv[]) { char *Str1 = "abaccdeff";//有序 char *Str2 = "aaaaaaa";//没有只出现一次的字符 char *Str3 = "bacffcde";//无序 char *Str4 = "fbacde";//无序且都只出现一次 cout << FirstNotRepeatChar(Str1) << endl; cout << FirstNotRepeatChar(Str2) << endl; cout << FirstNotRepeatChar(Str3) << endl; cout << FirstNotRepeatChar(Str4) << endl; system("pause"); return 0; }
运行结果: