leetcode@ [316] Remove Duplicate Letters (Stack & Greedy)

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

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

Example:

Given "bcabc"
Return "abc"

Given "cbacdcbc"
Return "acdb"

public class Solution {
    public String removeDuplicateLetters(String s) {
        
        int[] remain = new int[26];
        for(int i=0; i<s.length(); ++i) {
            remain[s.charAt(i) - 'a']++;
        }
        
        LinkedList<Character> stack = new LinkedList<Character> ();
        HashSet<Character> onStack = new HashSet<Character> ();
        for(int i=0; i<s.length(); ++i) {
            char ch = s.charAt(i);
            if(onStack.contains(ch)) {
                remain[ch-'a']--;
                continue;
            }
            
            while(!stack.isEmpty() && stack.peekFirst() > ch && remain[stack.peekFirst()-'a'] > 0) {
                onStack.remove(stack.peekFirst());
                // System.out.println("poll " + stack.peekFirst() + " out of stack!");
                stack.pollFirst();                    
            }
            
            remain[ch-'a']--;
            stack.addFirst(ch);
            // System.out.println("add " + ch + " into stack!");
            onStack.add(ch);
        }
        
        StringBuffer sb = new StringBuffer();
        while(!stack.isEmpty()) {
            char ch = stack.pollLast();
            sb.append(ch);
        }
        return sb.toString();
    }
}
View Code
原文地址:https://www.cnblogs.com/fu11211129/p/5625696.html