题目描述:
在字符串中找出第一个只出现一次的字符。如输入“abaccdeff”,则输出为‘b’.
思路分析:
统计每个字符出现的次数。字符(char)是一个长度为8的数据类型,因此总共有256中可能,所以我们可以使用一个长度为256的数组,每个字母根据起ascii码值作为数组的下表,对应数组的值存储每个字符出现的次数。
需要两次扫描字符串。第一次统计每个字符出现的次数。第二次查找字符对应的次数第一个为1的。
时间复杂度:O(n)
空间复杂度:O(1)
代码:
#include <iostream>
using namespace std;
//在字符串中查找第一个只出现一次的字符串
char FirstNotRepeatingChar(char * pString) {
if(pString == NULL)
return '\0';
const int tableSize = 256;
unsigned int hashTable[ tableSize ]; //哈希表的key是数组下标(字符的ascii值),value是数组的值(对应下表代表的字符出现的次数)
for (int i = 0; i < tableSize; ++i)
{
hashTable[i] = 0;
}
char *pHashKey = pString;
while( *(pHashKey) != '\0') { //遍历字符串,计算每个字符出现的次数,将次数存入hashTable
hashTable[ *pHashKey ] ++; //*****
pHashKey ++;
}
pHashKey = pString;
while( *pHashKey != '\0') { //遍历字符串,查找出现次数第一个为1的
if( hashTable[ *pHashKey ] == 1 )
return *pHashKey;
pHashKey ++;
}
return '\0';
}
void test1() { //字符串中存在只出现一次的字符
cout << "*****test1 字符串中存在只出现一次的字符:*****";
char * pString = "abcdbbad";
char res = FirstNotRepeatingChar(pString);
cout << res << endl;
}
void test2() { //字符串中不存在只出现一次的字符
cout << "*****test2 字符串中不存在只出现一次的字符:*****";
char * pString = "abcdbbadc";
char res = FirstNotRepeatingChar(pString);
cout << res << endl;
}
void test3() { //字符串中所有字符都只出现一次
cout << "*****test3 字符串中所有字符均只出现一次:*****";
char * pString = "abcdefgh";
char res = FirstNotRepeatingChar(pString);
cout << res << endl;
}
void test4() { //字符串为NULL指针
cout << "*****test3 字符串为NULL指针:*****";
char * pString = NULL;
char res = FirstNotRepeatingChar(pString);
cout << res << endl;
}
int main() {
test1();
test2();
test3();
test4();
return 0;
}
举一反三:
判断多个字符是不是在某个字符串中出现过或者统计多个字符在某个字符串中出现的次数,可以考虑基于数组创建一个简单的哈希表。这样可以用很小的空间消耗换来时间效率的提升。
下一篇博客是一个扩展的例子,有兴趣可以看看。