码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Remove Duplicate Letters" !!

时间:2016-01-27 08:12:33      阅读:195      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!