-
Notifications
You must be signed in to change notification settings - Fork 1
/
050_02-字符流中第一个只出现一次的字符.cpp
43 lines (40 loc) · 1.02 KB
/
050_02-字符流中第一个只出现一次的字符.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
class Solution{
public:
//Insert one char from stringstream
Solution():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;
int minIndex = INT_MAX;
for(int i = 0; i < 256; ++i)
{
if(occurrence[i] >= 0 && occurrence[i] < minIndex)
{
ch = (char) i;
minIndex = occurrence[i];
}
}
if(minIndex == INT_MAX)
return '#';
else
return ch;
}
private:
int index;
// 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];
};