在字符串中找到一个只出现一次的字符。如输入“abaccdeff” 输出结果为'b'。
最直观的想法就是从头开始扫描这个字符串中的每个字符。当访问到某个字符的时候拿这个字符和后面的每个字符相比较,如果在后面没有发现重复的字符,则该字符就是只出现一次的字符,不过这种方法时间复杂度是O(n*n)。
我们可以定义一个哈希表,哈希表的键值是字符,而值是数字。然后扫描字符串两次,第一次扫描字符串时,每扫描到一个字符的时候,就在哈希表的对应项中把次数加1.接下来第二次扫描时,每扫描到一个字符就从哈希表中得到该字符的个数。
我们创建一个长度为256的数组,因为char类型嘛,这种方法的时间复杂度是O(n)。
// FirstNotRepeatingChar.cpp : Defines the entry point for the console application.
//
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 著作权所有者:何海涛
#include <stdio.h>
#include <string>
char FirstNotRepeatingChar(char* pString)
{
if(pString == NULL)
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;
while(*pHashKey != '\0')
{
if(hashTable[*pHashKey] == 1)
return *pHashKey;
pHashKey++;
}
return '\0';
}
// ====================测试代码====================
void Test(char* pString, char expected)
{
if(FirstNotRepeatingChar(pString) == expected)
printf("Test passed.\n");
else
printf("Test failed.\n");
}
int main()
{
// 常规输入测试,存在只出现一次的字符
Test("google", 'l');
// 常规输入测试,不存在只出现一次的字符
Test("aabccdbd", '\0');
// 常规输入测试,所有字符都只出现一次
Test("abcdefg", 'a');
// 鲁棒性测试,输入NULL
Test(NULL, '\0');
return 0;
}