剑指offer面试题35

来源:互联网 发布:砧板 知乎 编辑:程序博客网 时间:2024/05/21 00:14

面试题35:第一个只出现一次的字符

题目:在字符串中找出第一个只出现一次的字符。如输入"abaccdeff",则输入'b'。

预备知识:

什么是哈希表?

思路:构造一个简单的基于数组的简单哈希表(key:字符,value:次数),字符的ASCII码作为字符的下标,统计次数作为数组值。

算法实现和测试:

// 面试题35.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"//第一个值出现一次的字符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;//第一扫描:这里把字符的ASCII值作为字符的下表了while(*pHashKey != '\0')hashTable[*(pHashKey++)] ++;pHashKey = pString;//第二次扫描while(*pHashKey != '\0'){if(hashTable[*pHashKey] == 1 )return *pHashKey;pHashKey++;}return '\0';}//*************测试代码**************void Test1(){char pStr[] = "abaccdeff";char ch = FirstNotRepeatingChar(pStr);printf("%c\n", ch);}void Test2(){char pStr[] = "abbaccddeeff";char ch = FirstNotRepeatingChar(pStr);printf("%c\n", ch);}void Test3(){char pStr[] = "abcdef";char ch = FirstNotRepeatingChar(pStr);printf("%c\n", ch);}//字符串为NULLvoid Test4(){char ch = FirstNotRepeatingChar(NULL);printf("%c\n", ch);}int _tmain(int argc, _TCHAR* argv[]){Test1();Test2();Test3();Test4();return 0;}



0 0
原创粉丝点击