-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathfirst_non_repeating_character.cpp
57 lines (50 loc) · 1.15 KB
/
first_non_repeating_character.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
/*Problem statement :
Print the first non repeating character in a running stream of characters,
that is the characters will input continuously until a '.'
is encountered you need to keep printing the first non repeating character. */
#include <bits/stdc++.h>
using namespace std;
void first_non_repeating(queue<char> q, int frequency[])
{
while (!q.empty())
{
int index = q.front() - 'a';
//If character already exists more than once, then pop
if (frequency[index] > 1)
{
q.pop();
}
else
{
cout << q.front() << endl;
break;
}
}
if (q.empty())
{
cout << "-1" << endl;
}
}
int main()
{
queue<char> q;
int frequency[27] = { 0 };
char ch;
cin >> ch;
while (ch != '.')
{
q.push(ch);
frequency[ch - 'a']++;
first_non_repeating(q,frequency);
cin >> ch;
}
return 0;
}
/*
Example :
1)Input = a a b c c .
Output = a -1 b b b
2)Input: s d d g .
Output: s s s s
Time Complexity : O(n)
Space Complexity : O(1) */