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();
    }
}

 

posted @ 2020-09-10 16:04  Sexyomaru  阅读(123)  评论(0编辑  收藏  举报