Remove Duplicate Letters

LeetCode Q 361- 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 1: Input: "bcabc" ; Output: "abc"
Example 2: Input: "cbacdcbc" ; Output: "acdb"

Solution:

Code:

public String removeDuplicateLetters(String s) {
  Deque<Character> stack = new ArrayDeque<>();
  int[] count = new int[26];
  boolean[] seen = new boolean[26]; 

  for (char ch: s.toCharArray()) count[ch - 'a']++;

  for (char ch: s.toCharArray()) {
    if (seen[ch]) continue;
    while (!stack.isEmpty && stack.peek() > ch && count[stack.peek() - 'a'] > 0)
      seen[stack.pop() - 'a'] = false;
    
    stack.push(ch);
    count[ch - 'a']--;
    seen[ch - 'a'] = true;
  }

  StringBuilder sb = new StringBuilder();
  while (!stack.isEmpty()) {
    sb.append(stack.removeLast());
  }
        
  return sb.toString();
}

   Reprint policy


《Remove Duplicate Letters》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC