[刷题防痴呆] 0316 - 去除重复字母 (Remove Du

2022-01-16  本文已影响0人  西出玉门东望长安

题目地址

https://leetcode.com/problems/remove-duplicate-letters/description/

题目描述

316. Remove Duplicate Letters

Given a string which contains only lowercase letters, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.

Example 1:

Input: "bcabc"
Output: "abc"
Example 2:

Input: "cbacdcbc"
Output: "acdb"
Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/

思路

关键点

代码

class Solution {
    public String removeDuplicateLetters(String s) {
        int[] lastIndex = new int[26];
        char[] sc = s.toCharArray();
        int n = sc.length;
        for (int i = 0; i < n; i++) {
            lastIndex[sc[i] - 'a'] = i;
        }
        Deque<Character> stack = new ArrayDeque<>();
        boolean[] visited = new boolean[26];
        for (int i = 0; i < n; i++) {
            char c = sc[i];
            if (visited[c - 'a']) {
                continue;
            }
            while (!stack.isEmpty() && stack.peek() > c && lastIndex[stack.peek() - 'a'] > i) {
                char pop = stack.pop();
                visited[pop - 'a'] = false;
            }
            stack.push(c);
            visited[c - 'a'] = true;
        }

        StringBuffer sb = new StringBuffer();
        while (!stack.isEmpty()) {
            sb.append(stack.pop());
        }
        return sb.reverse().toString();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读