Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //{ Driver Code Starts
- #include<bits/stdc++.h>
- using namespace std;
- // } Driver Code Ends
- class Solution {
- public:
- string FirstNonRepeating(string A){
- // Code here
- deque<int> q;
- unordered_map<char,int> m;
- string ans="";
- for(int i=0;i<A.length();i++)
- {
- m[A[i]]++;
- if(m[A[i]]>1)
- {
- if(!q.empty() && q.back()==A[i])
- {
- if(!q.empty())
- {
- q.pop_back();
- }
- if(q.empty())
- {
- ans+='#';
- }
- else
- {
- ans+=q.front();
- }
- }
- else
- {
- if(ans.size()>0 && ans[ans.length()-1]==A[i])
- {
- while(!q.empty() && m[q.front()]!=1)
- {
- q.pop_front();
- }
- }
- ans+=q.front();
- }
- }
- else
- {
- q.push_back(A[i]);
- if(A[i]==q.front())
- {
- ans+=A[i];
- }
- else
- {
- ans+=q.front();
- }
- }
- }
- return ans;
- }
- };
- //{ Driver Code Starts.
- int main(){
- int tc;
- cin >> tc;
- while(tc--){
- string A;
- cin >> A;
- Solution obj;
- string ans = obj.FirstNonRepeating(A);
- cout << ans << "\n";
- }
- return 0;
- }
- // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment