LeetCode-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"
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
Analysis:
We maintain a smallest valid char list and iterate through the whole string. When we move to the next char, we want to put it as ahead as possible in the valid char list so we want to remove all chars that are larger than it straing from the tail, e.g., "acd" and the next char is 'b', we then want to put it after 'a'; however, whether we can remove 'd' and 'c' depends on whether there are still 'b' and 'c' in the left string, if yes, then we can safely remove them.
Also, if we cannot remove 'd', then we cannot remove any chars in front of 'd', because this will actually enlarge the lexicographical order. e.g., "acd" and the following is "bc", if we remove "c", then the result is "adbc" which is larger than "acdb".
Solution:
1 public class Solution { 2 public String removeDuplicateLetters(String s) { 3 if (s.length() == 0) 4 return s; 5 6 int[] charCount = new int[26]; 7 boolean[] inStack = new boolean[26]; 8 Arrays.fill(charCount, 0); 9 Arrays.fill(inStack, false); 10 char[] charArray = s.toCharArray(); 11 for (char c : charArray) { 12 charCount[c - 'a']++; 13 } 14 15 Stack<Character> resStack = new Stack<Character>(); 16 for (char c : charArray) { 17 int index = c - 'a'; 18 charCount[index]--; 19 20 if (inStack[index]) 21 continue; 22 23 while (!resStack.isEmpty() && resStack.peek() > c && charCount[resStack.peek() - 'a'] > 0) { 24 inStack[resStack.pop() - 'a'] = false; 25 } 26 27 resStack.push(c); 28 inStack[index] = true; 29 } 30 31 StringBuilder builder = new StringBuilder(); 32 while (!resStack.isEmpty()) { 33 builder.append(resStack.pop()); 34 } 35 return builder.reverse().toString(); 36 } 37 }