316. 去除重复字母(栈)

class Solution {
    public String removeDuplicateLetters(String s) {
        int n = s.length();
        if(n <= 1) return s;
        Stack<Character> stack = new Stack<>();
        for(int i = 0; i < n; i++) {
            if(stack.contains(s.charAt(i))) continue;
            while(!stack.empty() && stack.peek() >= s.charAt(i) && s.substring(i).indexOf(stack.peek()) != -1) {
                stack.pop();
            }
            stack.push(s.charAt(i));
        }
        StringBuilder sb = new StringBuilder();
        while(!stack.empty()) {
            sb.append(stack.pop());
        }
        return sb.reverse().toString();
    }
}
原文地址:https://www.cnblogs.com/yonezu/p/13646291.html