-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path50_01_FirstNotRepeatingChar.cpp
More file actions
73 lines (56 loc) · 1.75 KB
/
50_01_FirstNotRepeatingChar.cpp
File metadata and controls
73 lines (56 loc) · 1.75 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题50(一):字符串中第一个只出现一次的字符
// 题目:在字符串中找出第一个只出现一次的字符。如输入"abaccdeff",则输出
// 'b'。
#include <cstdio>
#include <string>
char FirstNotRepeatingChar(const char* pString)
{
if(pString == nullptr)
return '\0';
const int tableSize = 256;
unsigned int hashTable[tableSize];
for(unsigned int i = 0; i < tableSize; ++i)
hashTable[i] = 0;
const char* pHashKey = pString;
while(*(pHashKey) != '\0')
hashTable[*(pHashKey++)] ++;
pHashKey = pString;
while(*pHashKey != '\0')
{
if(hashTable[*pHashKey] == 1)
return *pHashKey;
pHashKey++;
}
return '\0';
}
// ====================测试代码====================
void Test(const char* pString, char expected)
{
if(FirstNotRepeatingChar(pString) == expected)
printf("Test passed.\n");
else
printf("Test failed.\n");
}
int main(int argc, char* argv[])
{
// 常规输入测试,存在只出现一次的字符
Test("google", 'l');
// 常规输入测试,不存在只出现一次的字符
Test("aabccdbd", '\0');
// 常规输入测试,所有字符都只出现一次
Test("abcdefg", 'a');
// 鲁棒性测试,输入nullptr
Test(nullptr, '\0');
return 0;
}