每日一题:LeetCode之去除重复字母

给你一个仅包含小写字母的字符串,请你去除字符串中重复的字母,使得每个字母只出现一次。需保证返回结果的字典序最小(要求不能打乱其他字符的相对位置)。

示例 1:

输入: “bcabc”
输出: “abc”
示例 2:

输入: “cbacdcbc”
输出: “acdb”

思路:使用栈,并且要使字典序最小,若栈顶元素大于当前元素并且栈顶元素不是唯一的,后续还会出现,则将栈顶元素弹出,将当前元素入栈。

public String removeDuplicateLetters(String s) {
     
        int len = s.length();
        // 特判
        if (len < 2) {
     
            return s;
        }

        // 记录是否在已经得到的字符串中
        boolean[] set = new boolean[26];

        // 记录每个字符出现的最后一个位置
        int[] lastAppearIndex = new int[26];
        for (int i = 0; i < len; i++) {
      
            lastAppearIndex[s.charAt(i) - 'a'] = i;
        }

        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < len; i++) {
     
            char currentChar = s.charAt(i);
            if (set[currentChar - 'a']) {
     
                continue;
            }

            while (!stack.empty() && stack.peek() > currentChar && lastAppearIndex[stack.peek() - 'a'] >= i) {
     
                char top = stack.pop();
                set[top - 'a'] = false;
            }

            stack.push(currentChar);
            set[currentChar - 'a'] = true;
        }

        StringBuilder stringBuilder = new StringBuilder();
        while (!stack.empty()) {
     
            stringBuilder.insert(0, stack.pop());
        }
        return stringBuilder.toString();
    }

你可能感兴趣的:(leetcode,java)