Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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;
    }
};
posted on 2016-01-27 07:47  Tonix  阅读(175)  评论(0编辑  收藏  举报