316. Remove Duplicate Letters, 1081. Smallest Subsequence of Distinct Characters

T: O(n), S:O(n)

```java
class Solution {
    public String removeDuplicateLetters(String s) {
        Stack<Character> stack = new Stack<>();
        boolean[] inStack = new boolean[26];
        int[] count = new int[26];

        for (char c : s.toCharArray()) {
            count[c - 'a']++;
        }

        for (char c : s.toCharArray()) {
            count[c - 'a']--;
            if (inStack[c - 'a']) { // already in stack, pass (left in stack is the ans, only remain one)
                continue;
            }
            while (!stack.isEmpty() && stack.peek() > c) {
                // if the char we want to remove is not only one, it can remove
                if (count[stack.peek() - 'a'] == 0) {
                    break;
                }
                inStack[stack.pop() - 'a'] = false;
            }
            stack.push(c);
            inStack[c - 'a'] = true;
        }
        StringBuilder result = new StringBuilder();
        while (!stack.isEmpty()) {
            result.append(stack.pop());
        }
        return result.reverse().toString();
    }
}

/*
bcabc

c
b
a
c -> pop
b -> pop

cba -> abc


bcac
-> ac
obviously, can't pop b
how to know? use count, scan entire, cal char count

when process a char, count[char]--
so when we want to pop, but count[char] == 0, we can't pop, because we don't have same char later

use inStack, inStack 就已經是答案了, 所以如果後面一樣的還有就丟了(只保留一個
1. remove duplicate, use boolean[26]
2. stack
3. use count[char]

T: O(n), S: O(n)
*/
```ja

Last updated