forked from yunshouhu/InterviewQuestions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
面试题35之第一个只出现一次的字符_FirstNotRepeatingChar.cpp
61 lines (46 loc) · 1.22 KB
/
面试题35之第一个只出现一次的字符_FirstNotRepeatingChar.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// 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 _tmain(int argc, _TCHAR* argv[])
{
// 常规输入测试,存在只出现一次的字符
Test("google", 'l');
// 常规输入测试,不存在只出现一次的字符
Test("aabccdbd", '\0');
// 常规输入测试,所有字符都只出现一次
Test("abcdefg", 'a');
// 鲁棒性测试,输入NULL
Test(NULL, '\0');
return 0;
}