public String removeDuplicateLetters(String s) {
        int[] cnt = new int[256];
        for (int i = 0; i < s.length(); ++i) ++cnt[s.charAt(i)];

        LinkedList<Character> stack = new LinkedList<Character>();
        boolean[] visited = new boolean[256];
        for (int i = 0; i < s.length(); ++i) {
            char ch = s.charAt(i);
            --cnt[ch];
            if (visited[ch]) continue;
            while (!stack.isEmpty() && ch < stack.getLast() && cnt[stack.getLast()] > 0) {
                visited[stack.removeLast()] = false;
            }
            stack.addLast(ch);
            visited[ch] = true;
        }

        StringBuilder sb = new StringBuilder();
        while (!stack.isEmpty()) sb.append(stack.removeFirst());
        return sb.toString();
    }