22. Remove Duplicate Letters

smallest-subsequence-of-distinct-characters

Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.

Example 1:

Input: s = "bcabc"
Output: "abc"

Example 2:

Input: s = "cbacdcbc"
Output: "acdb"

Solution: (Using Stack)

class Solution
{
public:
    string removeDuplicateLetters(string s)
    {

        int n = s.length();
        vector<int> count(26, 0);
        vector<bool> vs(26, false);

        stack<char> st;

        for (int i = 0; i < s.length(); i++)
        {
            count[s[i] - 97]++;
        }

        st.push(s[0]);
        vs[s[0] - 97] = 1;
        count[s[0] - 97]--;

        for (int i = 1; i < s.length(); i++)
        {

            if (!vs[s[i] - 97])
            {

                while (!st.empty() && s[i] < st.top() && count[st.top() - 97] != 0)
                {
                    vs[st.top() - 97] = 0;
                    st.pop();
                }
                
                st.push(s[i]);
                vs[s[i] - 97] = 1;
            }
            count[s[i] - 97]--;
        }

        string res = "";
        while (!st.empty())
        {
            char ch = st.top();
            res = ch + res;
            st.pop();
        }

        return res;
    }
};

Last updated