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 {
public String removeDuplicateLetters(String s) {
int occur[] = new int[128];
int instack[] = new int[128];
for(int i = 0; i < s.length(); i++) occur[(int)s.charAt(i)]++;
char[] stack = new char[s.length()];
int len = 0;
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
occur[(int)c]--;
if(instack[(int)c] == 1) continue;
while(len > 0 && stack[len-1] > c && occur[stack[len-1]] > 0) {
instack[(int)stack[len-1]] = 0;
len--;
}
stack[len++] = c;
instack[(int)c] = 1;
}
StringBuilder sb = new StringBuilder();
for(int i = 0; i < len; i++) sb.append(stack[i]);
return sb.toString();
}
}