Problem
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”
Solution
public class Solution {
/**
* @param s: a string
* @return: return a string
*/
public String removeDuplicateLetters(String s) {
// write your code here
int[] count = new int[26]; // char-`a`
char[] stack = new char[26]; // index
boolean[] inStack = new boolean[26]; // char-`a`
for (char ch: s.toCharArray()) count[ch-`a`]++;
int index = 0;
for (char ch: s.toCharArray()) {
count[ch-`a`]--;
if (!inStack[ch-`a`]) {
//check the stack: if has larger element
while (index > 0 && stack[index-1] > ch && count[stack[index-1]-`a`] > 0) {
index--;
inStack[stack[index]-`a`] = false;
}
stack[index++] = ch;
inStack[ch-`a`] = true;
}
}
return new String(stack, 0, index);
}
}