316. Remove Duplicate Letters

Return the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once.

Note: This question is the same as 316: https://leetcode.com/problems/remove-duplicate-letters/

Example 1:

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

Example 2:

Input: s = "cbacdcbc"
Output: "acdb"
class Solution {
    public String smallestSubsequence(String s) {
        if(s.length() <= 1) return s;
        Stack<Character> stack = new Stack();
        int[] freq = help(s);
        
        for(char c : s.toCharArray()){
            freq[c - 'a']--;
            if(stack.contains(c)) continue;
            while(!stack.isEmpty() && stack.peek() > c && freq[stack.peek() - 'a'] > 0) 
                stack.pop();
            stack.push(c);
        }
        StringBuilder sb = new StringBuilder();
              while (!stack.isEmpty()) {
            sb.append(stack.pop());
        }
        
        return sb.reverse().toString();
       // return sb.toString();
    } 
    public int[] help(String s){
        int[] res = new int[26];
        for(char c : s.toCharArray()){
            res[c - 'a']++;
        }
        return res;
    }
}
原文地址:https://www.cnblogs.com/wentiliangkaihua/p/13800711.html