第一个只出现一次的字符
题目:在一个字符串中找到第一个只出现一次的字符。如输入abaccdeff,则输出b。
分析:这道题是2006年google的一道笔试题。
#include "stdio.h" char FirstNotRepeatingChar(char* pString) { unsigned int i; // invalid input if(!pString) return 0; // get a hash table, and initialize it const int tableSize = 256; unsigned int hashTable[tableSize]; for(i = 0; i < tableSize; ++ i) hashTable[i] = 0; // get the how many times each char appears in the string char* pHashKey = pString; while(*(pHashKey) != '\0') hashTable[*(pHashKey++)] ++; // find the first char which appears only once in a string pHashKey = pString; while(*pHashKey != '\0') { if(hashTable[*pHashKey] == 1) return *pHashKey; pHashKey++; } // if the string is empty // or every char in the string appears at least twice return 0; } int main() { printf("%c",FirstNotRepeatingChar("abaccdeff")); return 0; }
例二:字符串其实就是字符数组,上面的例一先来一个小例子
#include "stdio.h" char FirstNotRepeatingChar(char* pString) { char* pHashKey = pString; while(*(pHashKey) != '\0') { printf("%c\n",*(pHashKey++)); } // find the first char which appears only once in a string } int main() { FirstNotRepeatingChar("abaccdeff"); return 0; }
a
b
c
等