面试题 35,第一个只出现一次的字符(利用ASCII码表实现 基于单子符的哈希表)

使用哈希表来记录字符出现的次数是比较常见的思路。
但是答案使用了ASCII值作为数组的下表,从而很简单地利用256长的数组实现了哈希表。
字符- '\0'就是下标。
实际上,可以直接使用字符作为数组的下表unsigned int HashTable[256]; HashTable['A'] = 1 是合法的,编译器会自动把 'A'转成ASCII码值,也就是说
HashTable['A'] = 1 和 HashTable['A'-'\0'] = 1 意思一样。
先扫描一遍,记下每个字符出现的个数。
再扫一遍,扫到第一个次数为1的字符即可输出。
边界情况:输入空串;输入没有只出现一次的字符的字符串。都返回NULL。
书上代码,代码中扫描字符串给哈希表赋值的那两行代码
while(*(pHashKey) != '\0') hashTable[*(pHashKey++)] ++;
简洁而精彩!
// FirstNotRepeatingChar.cpp : Defines the entry point for the console application. // // 《剑指Offer——名企面试官精讲典型编程题》代码 // 著作权所有者:何海涛 #include "stdafx.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; }
使用哈希来存储字符出现的次数我已经知道,但这道题使用ASCII码来实现简单哈希,虽然简单,但是我确实没有想到。
以后解这种题,解法就更加完善了。
------------------------------------------------
Felix原创,转载请注明出处,感谢博客园!
posted on 2014-01-27 12:15 Felix Fang 阅读(393) 评论(0) 收藏 举报
浙公网安备 33010602011771号