思路
既然空间复杂度要求O(1),那么我们只能建立常数倍的空间。所以又因为是字符,所以可以使用一个大小为256的数组。用它来当哈希表。所以我的解法中申请了一个pair的键值对的数组。first保存的是出现的次数,second保存的是出现的该字符第一次出现在字符串中的下标。所以我们可以遍历一边字符串,我们就可以得到所以字符出现的次数和该字符第一次出现的下标。再遍历一次数组,定义一个min变量,遍历一边数组,就找到第一次出现2次的字符了。
代码
char Findfirstsecond(char * p)
{
assert(p != NULL);
if (*p == 0) return -1;
pair<unsigned int,int> hashtable[256]; //first为出现的次数,second为第一次出现时的下标
char * pCur = p;
size_t count = 0;
for (size_t idx = 0; idx < 256; idx++) // 首先给所以出现的下标赋值为-1
{
hashtable[idx].second = -1;
}
while (*pCur != 0)
{
hashtable[*pCur].first++;
if (hashtable[*pCur].second<0) //如果该字符第一次遍历到就保存它的下标
hashtable[*pCur].second = count;
pCur++;
count++;
}
int min = -1;
for (size_t idx = 0; idx < 256; idx++)
{
if (min < 0 && hashtable[idx].first == 2)
{
min = hashtable[idx].second;
}
else{
if (hashtable[idx].first == 2 && min > hashtable[idx].second)
{
min = hashtable[idx].second;
}
}
}
return (min<0)?min:*(p+min);
}