力扣labuladong——一刷day29

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 前言
  • 一、力扣316. 去除重复字母
  • 二、力扣1081. 不同字符的最小子序列


有序数组原地去重

前言


一、力扣316. 去除重复字母

class Solution {
    public String removeDuplicateLetters(String s) {
        Deque<Character> deq = new LinkedList<>();
        int[] nums = new int[256];
        boolean[] isFlag = new boolean[256];
        for(char c : s.toCharArray()){
            nums[c] ++;
        }
        for(char c : s.toCharArray()){
            nums[c] --;
            if(isFlag[c]){
                continue;
            }
            while(!deq.isEmpty() && deq.peekLast() > c){
                if(nums[deq.peekLast()] == 0){
                    break;
                }
                isFlag[deq.peekLast()] = false;
                deq.pollLast();
            }
            isFlag[c] = true;
            deq.offerLast(c);
        }
        StringBuilder sb = new StringBuilder();
        while(!deq.isEmpty()){
            sb.append(deq.pollLast());
        }
        return sb.reverse().toString();
    }
}

二、力扣1081. 不同字符的最小子序列

class Solution {
    public String smallestSubsequence(String s) {
        int[] count = new int[256];
        boolean[] flag = new boolean[256];
        Deque<Character> deq = new LinkedList<>();
        for(char c : s.toCharArray()){
            count[c] ++;
        }
        for(char c : s.toCharArray()){
            count[c] --;
            if(flag[c]){
                continue;
            }
            while(!deq.isEmpty() && deq.peekLast() > c){
                if(count[deq.peekLast()] == 0){
                    break;
                }
                flag[deq.pollLast()] = false;
            }
            flag[c] = true;
            deq.offerLast(c);
        }
        StringBuilder sb = new StringBuilder();
        while(!deq.isEmpty()){
            sb.append(deq.pollLast());
        }
        return sb.reverse().toString();
    }
}

你可能感兴趣的:(力扣题解,leetcode,算法,java,数据结构)