LeetCode "Remove Duplicate Letters" !!

Interesting Greedy.. classic

https://leetcode.com/discuss/75529/c-simple-solution-easy-understanding

class Solution 
{
public:
    string removeDuplicateLetters(string s) 
    {
        vector<int>  cnt(26);
        vector<bool> visited(26, false);

        //    Count
        for(char c : s)    cnt[c - 'a'] ++;

        stack<char> st;        
        for(char c : s)
        {
            int inx = c - 'a';
            
            cnt[inx]--;
            if(visited[inx]) continue;

            //    Greedy: we keep lexi-inc at every step. Greedy sort
            //            we pop it as long previous choice is larger in ASCII and not the last.
            while (!st.empty() && c < st.top() && cnt[st.top() - 'a'] != 0)
            {
                visited[st.top() - 'a'] = false;
                st.pop();
            }

            st.push(c);
            visited[inx] = true;
        }

        string ret;
        while(!st.empty())
        {
            ret = st.top() + ret;
            st.pop();
        }
        return ret;
    }
};
原文地址:https://www.cnblogs.com/tonix/p/5162049.html