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.
Subscribe to see which companies asked this question.
public class Solution {
public String removeDuplicateLetters(String s) {
int[] cnt=new int[256];
char[] str=s.toCharArray();
for(char c:str)cnt[c]++;
boolean[] visit=new boolean[256];
Stack<Character> st=new Stack<Character>();
for(char c:str){
cnt[c]--;
if(st.isEmpty()){
visit[c]=true;
st.push(c);
continue;
}else{
if(visit[c])continue;
while((!st.empty())&&c<st.peek()&&cnt[st.peek()]>=1){
char ct=st.pop();
//cnt[ct]++;
visit[ct]=false;
}
st.push(c);
visit[c]=true;
}
}
StringBuffer res=new StringBuffer();
while(!st.isEmpty())res.append(st.pop());
res.reverse();
return res.toString();
}
}
时间复杂度:O(N)