LeetCode-不同字符的最小子序列

163 阅读1分钟

算法记录

LeetCode 题目:

  返回 s 字典序最小的子序列,该子序列包含 s 的所有不同字符,且只包含一次。


说明

一、题目

  s 由小写英文字母组成

二、分析

  • 如果没有最小字典序这个约束条件的话就直接进行一个去重输出即可,但是偏偏有这么一个条件在里面。
  • 最小字典序指的就是排在前面的字符的字典序要相对较小,那不就回归到一个单调性的特点上来了。
  • 维护一个单调栈用来记录字典序,一个数组来记录字符出现的次数,一个集合来判断当前的字符有没有已经放入到栈中。
class Solution {
    public String smallestSubsequence(String s) {
        Deque<Character> queue = new LinkedList();
        int[] map = new int[26];
        Set<Character> set = new HashSet();
        for(char c : s.toCharArray()) map[c - 'a']++;
        for(char c : s.toCharArray()) {
            if(!set.contains(c)) {
                while(!queue.isEmpty() && 
                        map[queue.peekLast() - 'a'] > 0 &&
                        c < queue.peekLast())
                    set.remove(queue.pollLast());  
                queue.add(c);
                set.add(c);  
            }
            map[c - 'a']--;
        }
        StringBuilder builder = new StringBuilder();
        while(!queue.isEmpty()) builder.append(queue.pollFirst());
        return builder.toString();
    }
}

总结

熟悉单调栈的使用方法以及字符的处理。