JZ-C-35

剑指offer第三十五题:第一个只出现一次的字符

 1 //============================================================================
 2 // Name        : JZ-C-35.cpp
 3 // Author      : Laughing_Lz
 4 // Version     :
 5 // Copyright   : All Right Reserved
 6 // Description : 第一个只出现一次的字符
 7 //============================================================================
 8 
 9 #include <iostream>
10 #include <stdio.h>
11 #include <string>
12 using namespace std;
13 
14 char FirstNotRepeatingChar(char* pString)
15 {
16     if(pString == NULL)
17         return '\0';
18 
19     const int tableSize = 256;
20     unsigned int hashTable[tableSize];//此处定义的哈希表中,key为字符,字符的ASCII码值为数组下标,value为字符出现次数,
21     for(unsigned int i = 0; i<tableSize; ++ i)
22         hashTable[i] = 0;
23 
24     char* pHashKey = pString;
25     while(*(pHashKey) != '\0')//第一次遍历字符串
26         hashTable[*(pHashKey++)] ++;//使哈希表中对应字符(数组下标为字符ASCII码值)的出现次数加1
27 
28     pHashKey = pString;//再将指针重新指向pString
29     while(*pHashKey != '\0')
30     {
31         if(hashTable[*pHashKey] == 1)//遇到第一个value为1的立即跳出循环,返回
32             return *pHashKey;
33 
34         pHashKey++;
35     }
36 
37     return '\0';
38 }
39 
40 // ====================测试代码====================
41 void Test(char* pString, char expected)
42 {
43     if(FirstNotRepeatingChar(pString) == expected)
44         printf("Test passed.\n");
45     else
46         printf("Test failed.\n");
47 }
48 
49 int main(int argc, char** argv)
50 {
51     // 常规输入测试,存在只出现一次的字符
52     Test("google", 'l');
53 
54     // 常规输入测试,不存在只出现一次的字符
55     Test("aabccdbd", '\0');
56 
57     // 常规输入测试,所有字符都只出现一次
58     Test("abcdefg", 'a');
59 
60     // 鲁棒性测试,输入NULL
61     Test(NULL, '\0');
62 
63     return 0;
64 }
posted @ 2016-06-21 18:17  回看欧洲  阅读(150)  评论(0编辑  收藏  举报