面试题35:第一个只出现一次的字符
来源:互联网 发布:制作特效视频软件 编辑:程序博客网 时间:2024/06/05 07:15
/*题目:在字符串中找出第一个只出现一次的字符,如输入"abaccdeff",则输出'b'。*/#include <iostream>using namespace std;//时间复杂度为O(n)空间复杂度为O(1)(利用一个固定大小的数组)char FirstNotReapeatChar(char *pString){ if(pString == NULL) return '\0'; const unsigned 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; while(*pHashKey != '\0') { if(hashtable[*pHashKey] == 1) return *pHashKey; ++pHashKey; } return '\0';}//================测试代码==============void Test(char *pString, char expected){ if(FirstNotReapeatChar(pString) == expected) cout << "Passed!" << endl; else cout << "Failed!" << endl;}int main(){ //常规输入测试,字符串中存在只出现一次的字符 Test("google", 'l'); //常规输入测试,不存在只出现一次的字符 Test("aabccdbd", '\0'); //常规输入册是,字符串中所有字符都只出现一次 Test("abcdefg", 'a'); // 鲁棒性测试,输入NULL Test(NULL, '\0'); return 0;}/*注:如果需要判断多个字符是不是在某个字符串里出现或者统计多个字符在某个字符串中出现的次数,可以考虑基于数组创建一个简单的哈希表。这样可以用很小的空间消耗换来时间效率的提升。*/