0316. Remove Duplicate Letters (M)

Remove Duplicate Letters (M)

题目

Given a string s, 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.

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

Example 1:

Input: s = "bcabc"
Output: "abc"

Example 2:

Input: s = "cbacdcbc"
Output: "acdb"

Constraints:

  • 1 <= s.length <= 10^4
  • s consists of lowercase English letters.

题意

删去字符串里重复的字母,使剩下的字母都只出现一次且得到的字符串在所有可能结果中字典序最小。

思路

先遍历一遍统计所有字母出现的次数。

再次遍历字符串,如果当前字符c已经安排在结果字符串s中,则跳过;若还未安排,将c与s中最后一个字符c'进行比较,如果c<c'且c'在之后还会出现,则删除c',重复该操作直到末尾所有满足的c'都被删除,最后将c加到s的末尾。


代码实现

Java

class Solution {
    public String removeDuplicateLetters(String s) {
        Deque<Character> deque = new ArrayDeque<>();
        int[] count = new int[26];
        boolean[] used = new boolean[26];

        for (char c : s.toCharArray()) {
            count[c - 'a']++;
        }

        for (char c : s.toCharArray()) {
            if (!used[c - 'a']) {
                while (!deque.isEmpty() && c < deque.peekLast() && count[deque.peekLast() - 'a'] > 0) {
                    used[deque.peekLast() - 'a'] = false;
                    deque.pollLast();
                }
                deque.offer(c);
                used[c - 'a'] = true;
            }
            count[c - 'a']--;
        }

        StringBuilder sb = new StringBuilder();
        while (!deque.isEmpty()) {
            sb.append(deque.poll());
        }
        return sb.toString();
    }
}
posted @ 2020-10-11 17:02  墨云黑  阅读(158)  评论(0编辑  收藏  举报