栈
public static String removeDuplicateLetters(String s) {
if (s==null) return "";
Deque<Character> stack=new ArrayDeque<>();
Map<Character,Integer> hash=new HashMap<>();
for (int i = 0; i < s.length(); i++) hash.put(s.charAt(i),i);
for (int i = 0; i < s.length(); i++) {
char c=s.charAt(i);
if (!stack.contains(c)){
while (!stack.isEmpty()&&stack.peek()>c&&hash.get(stack.peek())>i-1){
stack.pop();
}
stack.push(c);
}
}
StringBuilder sb=new StringBuilder();
while (!stack.isEmpty()){
sb.append(stack.removeLast());
}
return sb.toString();
}
学有所思
击败率不是很高,后期我再优化吧!