题目链接:https://leetcode.com/problems/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"
思路:
参考discuss做的。。。。。。。
思路简单直接 如果当前字符cur 比栈顶字符还小,且栈顶元素在cur之后还会再出现,那么栈顶元素没必要保存,出栈
算法:
public String removeDuplicateLetters(String s) {
Stack<Character> stack = new Stack<>();
int[] map = new int[26];
boolean visited[] = new boolean[26];
String res = "";
for (char c : s.toCharArray()) {
map[c - 'a']++;
}
for (int i = 0; i < s.length(); i++) {
map[s.charAt(i)-'a']--;
if(visited[s.charAt(i)-'a'])
continue;
//当前字符比栈顶还小,且栈顶在该字符后面还有出现过,所以当前字符应该在前面
while(!stack.isEmpty()&&stack.peek()>s.charAt(i)&&map[stack.peek()-'a']>0){
visited[stack.peek()-'a']=false;
stack.pop();
}
stack.push(s.charAt(i));
visited[s.charAt(i)-'a'] = true;
}
while(!stack.isEmpty()){
res= stack.pop()+res;
}
return res;
}