https://leetcode-cn.com/problems/remove-duplicate-letters/
示例 1:
输入:s = "bcabc" 输出:"abc"示例 2:
输入:s = "cbacdcbc" 输出:"acdb"推荐题解:https://labuladong.gitbook.io/algo/shu-ju-jie-gou-xi-lie/dan-tiao-zhan-qu-zhong 注意题目的三个点就好: 1.去重 2.保留相对位置 3.满足前两个条件的情况下字典序最小
class Solution { public String removeDuplicateLetters(String s) { LinkedList<Character> stack = new LinkedList<>(); int[] count = new int[256]; for (int i = 0; i < s.length(); i++) { count[s.charAt(i)]++; } boolean[] inStack = new boolean[256]; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); count[c]--; if (inStack[c]) continue; while (!stack.isEmpty() && stack.peek() > c) { if (count[stack.peek()] == 0) { break; } inStack[stack.pop()] = false; } stack.push(c); inStack[c] = true; } StringBuilder sbu = new StringBuilder(); while (!stack.isEmpty()) { sbu.append(stack.pop()); } return sbu.reverse().toString(); } }