Java Concise Solution


  • 0
    public class Solution {
        public String removeDuplicateLetters(String s) {
            if (s == null || s.length() < 2) return s;
            Stack<Character> stack = new Stack<>();
            Set<Character> existing = new HashSet<>();
            int[] count = new int[26];
            for (char c : s.toCharArray()) {
                count[c -  'a']++;
            }
            for (char c : s.toCharArray()) {
                count[c - 'a']--;
                if (!existing.add(c)) continue;
                while (!stack.isEmpty() && c < stack.peek() && count[stack.peek() - 'a'] > 0) {
                    existing.remove(stack.pop());
                }
                stack.push(c);
            }
            String res = "";
            while (!stack.isEmpty()) {
                res = stack.pop() + res;
            }
            return res;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.