您的位置:首页 > 其它

查找一个字符串中第一个只出现两次的字符。比如:“abcdefabcdefabc”中第一个只出现两次为‘d’,要求时间复杂度为O(N),空间复杂度为O(1)

2017-07-20 00:05 330 查看
char FirstTwiceChar(char* string)
{
if (string == NULL)
return '\0';
const int tableSize = 256; //char类型的长度为8位,一共就256种可能
unsigned int hashTable[tableSize];
for (unsigned int i = 0; i<tableSize; ++i) //初始化数组
hashTable[i] = 0;

char* pHashKey = string;
while (*pHashKey != '\0')
hashTable[*(pHashKey++)]++;

pHashKey = string;
while (*pHashKey != '\0')
{
if (hashTable[*pHashKey] == 2)
return *pHashKey;

pHashKey++;
}
return '\0';
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐