<p>Given a string <code>s</code>, remove duplicate letters so that every letter appears once and only once. You must make sure your result is <span data-keyword="lexicographically-smaller-string"><strong>the smallest in lexicographical order</strong></span> among all possible results.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;bcabc&quot;
<strong>Output:</strong> &quot;abc&quot;
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;cbacdcbc&quot;
<strong>Output:</strong> &quot;acdb&quot;
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li>
	<li><code>s</code> consists of lowercase English letters.</li>
</ul>

<p>&nbsp;</p>
<p><strong>Note:</strong> This question is the same as 1081: <a href="https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/" target="_blank">https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/</a></p>

class Solution {
public:
    string removeDuplicateLetters(string s) {
        int n = s.length();
        string ans = "";
        vector<int> lastOcc(26, -1);
        vector<bool> visited(26, false);
        stack<char> st;
        for (int i = n - 1; i >= 0; i--) {
            if (lastOcc[s[i] - 'a'] == -1) {
                lastOcc[s[i] - 'a'] = i;
            }
        }
        for (int i = 0; i < n; i++) {
            char x = s[i];
            if (st.empty()) {
                st.push(x);
                visited[x - 'a'] = true;
                continue;
            }
            while (!st.empty() && s[i] < st.top() && lastOcc[st.top() - 'a'] > i && !visited[s[i] - 'a']) {
                visited[st.top() - 'a'] = false;
                st.pop();
            }
            
            if (visited[s[i] - 'a'] == false) {
                visited[s[i] - 'a'] = true;
                st.push(s[i]);
            }
        }
        while (!st.empty()) {
            ans += st.top();
            st.pop();
        }

        reverse(ans.begin(), ans.end());
        return ans;
    }
};
8700