首页 > 其他 > 详细

LeetCode "Remove Duplicate Letters" !!

时间:2016-01-27 08:09:29      阅读:134      评论:0      收藏:0      [点我收藏+]

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;
    }
};

LeetCode "Remove Duplicate Letters" !!

原文:http://www.cnblogs.com/tonix/p/5162049.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!