Remove Duplicate Letters in C++

C++Server Side ProgrammingProgramming

Suppose we have a string consisting of only lowercase letters. We have to remove all duplicate letters such that all letters only occur once. And we have to display the result in the smallest lexicographic sequence. So if the input is like “abccb”, then the result will be “abc”

To solve this, we will follow these steps −

  • ans := one empty string

  • Define one stack st

  • Define an array onStack of size 26

  • Define one map m

  • n := size of s

  • for initializing i := 0, when i < n, increase i by 1 do −

    • increase m[s[i]] by 1

  • for initializing i := 0, when i < n, increase i by 1 do −

    • Define an array x = s of size i

    • decreae m[x] by 1

    • if onStack[x - 'a'] is non-zero, then,

      • Skip to the next iteration, ignore the following part

    • while st is not empty and x < st.top(), do −

      • onStack[top of st - 'a'] := false

      • delete item from st

    • insert x into st

    • onStack[x - 'a'] := true

  • while (st is empty) is false, do −

    • x := top element of st

    • delete item from st

    • ans = ans + x

  • reverse the array rev

  • return ans

Example

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
   public:
   string removeDuplicateLetters(string s) {
      string ans = "";
      stack <char> st;
      vector <int> onStack(26);
      map <char, int> m;
      int n = s.size();
      for(int i = 0; i < n; i++){
         m[s[i]]++;
      }
      for(int i = 0; i < n; i++){
         char x = s[i];
         m[x]--;
         if(onStack[x - 'a'])continue;
         while(!st.empty() && x < st.top() && m[st.top()]){
            onStack[st.top() - 'a'] = false;
            st.pop();
         }
         st.push(x);
         onStack[x - 'a'] = true;
      }
      while(!st.empty()){
         char x = st.top();
         st.pop();
         ans += x;
      }
      reverse(ans.begin(), ans.end());
      return ans;
   }
};
main(){
   Solution ob;
   cout << (ob.removeDuplicateLetters("abccb"));
}

Input

“abccb”

Output

“abc”
raja
Published on 27-May-2020 06:08:11
Advertisements