jayati

first non repeating character code failing on some test cases

Oct 10th, 2023
702
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.77 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.             deque<int> q;
  11.             unordered_map<char,int> m;
  12.             string ans="";
  13.             for(int i=0;i<A.length();i++)
  14.             {
  15.                 m[A[i]]++;
  16.                 if(m[A[i]]>1)
  17.                 {
  18.                     if(!q.empty() && q.back()==A[i])
  19.                     {
  20.                         if(!q.empty())
  21.                     {
  22.                          q.pop_back();
  23.                     }
  24.                    
  25.                     if(q.empty())
  26.                     {
  27.                       ans+='#';
  28.                     }
  29.                     else
  30.                     {
  31.                         ans+=q.front();
  32.                     }
  33.                        
  34.                     }
  35.                    
  36.                     else
  37.                     {
  38.                          if(ans.size()>0 && ans[ans.length()-1]==A[i])
  39.                          {
  40.                              while(!q.empty() && m[q.front()]!=1)
  41.                              {
  42.                                q.pop_front();
  43.                               }
  44.                              
  45.                          }
  46.                        
  47.                        
  48.                        
  49.                        
  50.                        ans+=q.front();
  51.                     }
  52.                    
  53.                    
  54.                 }
  55.                 else
  56.                 {
  57.                     q.push_back(A[i]);
  58.                     if(A[i]==q.front())
  59.                     {
  60.                         ans+=A[i];
  61.                     }
  62.                     else
  63.                     {
  64.                         ans+=q.front();
  65.                     }
  66.                 }
  67.             }
  68.             return ans;
  69.         }
  70.  
  71. };
  72.  
  73. //{ Driver Code Starts.
  74. int main(){
  75.     int tc;
  76.     cin >> tc;
  77.     while(tc--){
  78.         string A;
  79.         cin >> A;
  80.         Solution obj;
  81.         string ans = obj.FirstNonRepeating(A);
  82.         cout << ans << "\n";
  83.     }
  84.     return 0;
  85. }
  86. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment