forked from yunshouhu/InterviewQuestions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
面试题55之字符流中第一个不重复的字符_FirstCharacterInStream.cpp
92 lines (72 loc) · 1.83 KB
/
面试题55之字符流中第一个不重复的字符_FirstCharacterInStream.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
* Question Description:
*/
#include <vector>
#include <limits>
using namespace std;
class CharStatistics
{
public:
CharStatistics() : index (0)
{
for(int i = 0; i < 256; ++i)
occurrence[i] = -1;
}
void Insert(char ch)
{
if(occurrence[ch] == -1)
occurrence[ch] = index;
else if(occurrence[ch] >= 0)
occurrence[ch] = -2;
index++;
}
char FirstAppearingOnce()
{
char ch = '\0';
int minIndex = numeric_limits<int>::max();
for(int i = 0; i < 256; ++i)
{
if(occurrence[i] >= 0 && occurrence[i] < minIndex)
{
ch = (char)i;
minIndex = occurrence[i];
}
}
return ch;
}
private:
// occurrence[i]: A character with ASCII value i;
// occurrence[i] = -1: The character has not found;
// occurrence[i] = -2: The character has been found for mutlple times
// occurrence[i] >= 0: The character has been found only once
int occurrence[256];
int index;
};
// ==================== Test Code ====================
void Test(char* testName, CharStatistics chars, char expected)
{
if(testName != NULL)
printf("%s begins: ", testName);
if(chars.FirstAppearingOnce() == expected)
printf("Passed.\n");
else
printf("FAILED.\n");
}
int main(int argc, char* argv[])
{
CharStatistics chars;
Test("Test1", chars, '\0');
chars.Insert('g');
Test("Test2", chars, 'g');
chars.Insert('o');
Test("Test3", chars, 'g');
chars.Insert('o');
Test("Test4", chars, 'g');
chars.Insert('g');
Test("Test5", chars, '\0');
chars.Insert('l');
Test("Test6", chars, 'l');
chars.Insert('e');
Test("Test7", chars, 'l');
return 0;
}