Remove Duplicate Letters

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

Example:

Given "bcabc"
Return "abc"

Given "cbacdcbc"
Return "acdb"


class Solution {
public:
    string removeDuplicateLetters(string s) {
        int n = s.length();
    
        vector<int> candidates(256, 0);
        vector<bool> visited(256, false);
        stack<char> buf;
        for (int i = 0; i < n; i++)
        {
            candidates[s[i]]++;
        }
        buf.push('0');
        for (int i = 0; i < n; i++)
        {
            candidates[s[i]]--;
            if (visited[s[i]])
            {
                continue;
            }   
            while (buf.top() > s[i] && candidates[buf.top()] > 0)
            {
                visited[buf.top()] = false;
                buf.pop();
            }

            buf.push(s[i]);
            visited[s[i]] = true;
        }   

        string result;
        while (buf.top() != '0')
        {
            result = buf.top() + result;
            buf.pop();
        }
        return result;
    }
};


你可能感兴趣的:(Remove Duplicate Letters)