classSolution{publicStringremoveDuplicates(String s){Deque<Character> stack =newLinkedList<>();for(int i =0; i < s.length(); i++){if(stack.isEmpty()){
stack.offerFirst(s.charAt(i));}else{if(stack.peekFirst()== s.charAt(i)){
stack.pollFirst();}else{
stack.offerFirst(s.charAt(i));}}}char[] chars =newchar[stack.size()];for(int i = chars.length -1; i >=0; i--){
chars[i]= stack.pollFirst();}returnnewString(chars);}}
150 逆波兰表达式
classSolution{publicintevalRPN(String[] tokens){Deque<Integer> stack =newLinkedList<>();for(String s : tokens){if(stack.isEmpty()){Integer i =Integer.valueOf(s);
stack.offerFirst(i);}else{if(s.equals("+")){Integer a = stack.pollFirst();Integer b = stack.pollFirst();
stack.offerFirst(b + a);}elseif(s.equals("-")){Integer a = stack.pollFirst();Integer b = stack.pollFirst();
stack.offerFirst(b - a);}elseif(s.equals("*")){Integer a = stack.pollFirst();Integer b = stack.pollFirst();
stack.offerFirst(b * a);}elseif(s.equals("/")){Integer a = stack.pollFirst();Integer b = stack.pollFirst();
stack.offerFirst(b / a);}else{Integer i =Integer.valueOf(s);
stack.offerFirst(i);}}}return stack.peekFirst();}}
单调队列
239 滑动窗口最大值
classSolution{/*
单调队列要用双端队列来实现
*/Deque<Integer> que =newLinkedList<>();publicint[]maxSlidingWindow(int[] nums,int k){int[] res =newint[nums.length - k +1];int count =0;for(int i =0; i < k; i++){push(nums[i]);}
res[count++]=max();for(int i = k; i < nums.length; i++){/**
先弹再加,要是先加再弹就会弹错
*/pop(nums[i - k]);push(nums[i]);
res[count++]=max();}return res;}/**
维护一个单调队列
*/voidpush(int x){/*
如果新进入队列的值比队列入口的值大的话,删除入口元素。
不能和出口元素比较,因为插入元素的大小可能会在出口元素和入口元素之间
*/while(!que.isEmpty()&& que.peekLast()< x){
que.pollLast();}
que.offerLast(x);}/*
弹出就弹出一个即可,因为可能又多个最大值
*/voidpop(int x){if(!que.isEmpty()&& x == que.peekFirst()){
que.poll();}}intmax(){return que.peekFirst();}}
优先队列(大顶堆or小顶堆)
347 前k个高频元素
classSolution{publicint[]topKFrequent(int[] nums,int k){Map<Integer,Integer> hashMap =newHashMap<>();for(Integer i : nums){
hashMap.put(i, hashMap.getOrDefault(i,0)+1);}/*
优先队列中放的是entry对象,将出现次数和值对应起来
*/Set<Map.Entry<Integer,Integer>> set = hashMap.entrySet();/**
构建小顶堆(先弹出小的,即小的数在队头,大顶堆相反)
从小到大的排序比较方式构成小顶堆
*/PriorityQueue<Map.Entry<Integer,Integer>> que =newPriorityQueue<>((o1, o2)-> o1.getValue()- o2.getValue());for(Map.Entry<Integer,Integer> entry : set){
que.offer(entry);if(que.size()> k){
que.poll();}}/**
获取结果
*/int[] res =newint[k];for(int i = k -1; i >=0; i--){
res[i]= que.poll().getKey();}return res;}}