提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
class MyQueue { Deque<Integer> deque = new LinkedList<>(); //弹出元素时,比较当前要弹出的数值是否等于队列出口的数值,如果相等则弹出 //同时判断队列当前是否为空 void poll(int val) { if (!deque.isEmpty() && val == deque.peek()) { deque.poll(); } } //添加元素时,如果要添加的元素大于入口处的元素,就将入口元素弹出 //保证队列元素单调递减 //比如此时队列元素3,1,2将要入队,比1大,所以1弹出,此时队列:3,2 void add(int val) { while (!deque.isEmpty() && val > deque.getLast()) { deque.removeLast(); } deque.add(val); } //队列队顶元素始终为最大值 int peek() { return deque.peek(); } }
一、力扣20. 有效的括号
class Solution {
Deque<Character> deq = new LinkedList<>();
public boolean isValid(String s) {
for(char c : s.toCharArray()){
if(c == '(' || c == '{' || c == '['){
deq.offerLast(c);
}else{
if(deq.isEmpty()){
return false;
}
char temp = deq.pollLast();
if(c == ')' && temp != '('){
return false;
}
if(c == '}' && temp != '{'){
return false;
}
if(c == ']' && temp != '['){
return false;
}
}
}
if(!deq.isEmpty()){
return false;
}
return true;
}
}
二、力扣1047. 删除字符串中的所有相邻重复项
class Solution {
public String removeDuplicates(String s) {
StringBuilder sb = new StringBuilder();
for(char c : s.toCharArray()){
if(sb.length() == 0){
sb.append(c);
}else{
if(sb.charAt(sb.length()-1) == c){
sb.deleteCharAt(sb.length()-1);
}else{
sb.append(c);
}
}
}
return sb.toString();
}
}
三、力扣150. 逆波兰表达式求值
class Solution {
public int evalRPN(String[] tokens) {
Deque<Integer> deq = new LinkedList<>();
for(String s : tokens){
if(s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")){
int right = deq.pollLast();
int left = deq.pollLast();
switch(s){
case "+":
deq.offerLast(left+right);break;
case "-":
deq.offerLast(left-right);break;
case "*":
deq.offerLast(left*right);break;
case "/":
deq.offerLast(left/right);break;
}
}else{
deq.offerLast(Integer.parseInt(s));
}
}
return deq.pollLast();
}
}
四、力扣239. 滑动窗口最大值
class Solution {
Deque<Integer> deq = new LinkedList<>();
public int[] maxSlidingWindow(int[] nums, int k) {
int[] res = new int[nums.length - k +1];
int left = 0, right = 0, t = 0;
while(right < nums.length){
if(right < k){
if(!deq.isEmpty()){
if(deq.peekLast() == nums[right]){
deq.offerLast(nums[right]);
}else if(deq.peekLast() < nums[right]){
while(!deq.isEmpty() && nums[right] > deq.peekLast()){
deq.pollLast();
}
deq.offerLast(nums[right]);
}else{
deq.offerLast(nums[right]);
}
}else{
deq.offerLast(nums[right]);
}
if(right == k-1){
res[t ++] = deq.peekFirst();
if(deq.peekFirst() == nums[left]){
deq.pollFirst();
}
left ++;
}
right ++;
}else{
if(!deq.isEmpty()){
if(deq.peekLast() == nums[right]){
deq.offerLast(nums[right]);
}else if(deq.peekLast() < nums[right]){
while(!deq.isEmpty() && nums[right] > deq.peekLast()){
deq.pollLast();
}
deq.offerLast(nums[right]);
}else{
deq.offerLast(nums[right]);
}
}else{
deq.offerLast(nums[right]);
}
res[t ++] = deq.peekFirst();
right ++;
if(deq.peekFirst() == nums[left]){
deq.pollFirst();
}
left ++;
}
}
return res;
}
}