import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param str string字符串 
     * @return string字符串
     */
    public String removeDuplicateLetters(String str) {
        // write code here
        int len = str.length();
        char[] chrs = str.toCharArray();
        boolean[] visiteds = new boolean[26];
        int[] lastIndexs = new int[26];
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < chrs.length; i++) {
            lastIndexs[chrs[i] - 'a'] = i;
        }
        for (int i = 0; i < chrs.length; i++) {
            if (visiteds[chrs[i] - 'a']) {
                continue;
            }
            while (!stack.isEmpty() && stack.peek() > chrs[i] && lastIndexs[stack.peek() - 'a'] > i) {
                char topChar = stack.pop();
                visiteds[topChar - 'a'] = false;
            }
            stack.push(chrs[i]);
            visiteds[chrs[i] - 'a'] = true;
        }
        StringBuffer sb = new StringBuffer("");
        while (!stack.isEmpty()) {
            sb.append(stack.pop());
        }
        sb.reverse();
        return new String(sb);
    }
}