jayati

First non-repeating character in a stream

Oct 10th, 2023
654
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.90 KB | None | 0 0
  1. //{ Driver Code Starts
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4.  
  5. // } Driver Code Ends
  6. class Solution {
  7.     public:
  8.         string FirstNonRepeating(string A){
  9.             // Code here
  10.            queue<int> q;
  11.            q.push(A[0]);
  12.            unordered_map<char,int> m;
  13.            m[A[0]]++;
  14.            int i=1;
  15.            string ans="";
  16.            ans+=A[0];
  17.            while(i<A.length())
  18.            {
  19.                m[A[i]]++;
  20.                q.push(A[i]);
  21.                while(m[q.front()]>1 && !q.empty())
  22.                {
  23.                    q.pop();
  24.                }
  25.                if(!q.empty())
  26.                {
  27.                    ans+=q.front();
  28.                }
  29.                else
  30.                {
  31.                    ans+='#';
  32.                }
  33.                i++;
  34.            }
  35.            return ans;
  36.            
  37.         }
  38.  
  39. };
  40.  
  41. //{ Driver Code Starts.
  42. int main(){
  43.     int tc;
  44.     cin >> tc;
  45.     while(tc--){
  46.         string A;
  47.         cin >> A;
  48.         Solution obj;
  49.         string ans = obj.FirstNonRepeating(A);
  50.         cout << ans << "\n";
  51.     }
  52.     return 0;
  53. }
  54. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment