Task: Find the first non repeating character in a stream, The steam is inserted one character at a time from given string. Print first non repeating character in every inserting time if no such character exist print -1.
Example:
Input:
1
3
a a c
Output:
a -1 c
Here is the Code:
Program in C++:
- #include<iostream>
- #include<bits/stdc++.h>
- using namespace std;
- map<char,int> m;
- queue<char> q;
- void fnrcInStream(char *a,int n)
- {
- for(int i=0;i<n;i++)
- {
- if(m.find(a[i])==m.end())
- {
- q.push(a[i]);
- }
- m[a[i]]++;
- if(m[q.front()]==1)
- {
- cout<<q.front()<<" ";
- }
- else
- {
- while(!q.empty())
- {
- q.pop();
- if(m[q.front()]==1)
- {
- cout<<q.front()<<" ";
- break;
- }
- }
- if(q.empty())
- {
- cout<<-1<<" ";
- }
- }
- }
- while(!q.empty())
- {
- q.pop();
- }
- m.clear();
- cout<<endl;
- }
- int main()
- {
- int t;
- cin>>t;
- while(t--)
- {
- int n;
- cin>>n;
- char a[n];
- for(int i=0;i<n;i++)
- {
- cin>>a[i];
- }
- fnrcInStream(a,n);
- }
- return 0;
- }
Here is the Video:
Comments
Post a Comment