The use of deque ArrayQueue

LeetCode20:
Given a string s that only includes'(',')','{','}','[',']', judge whether the string is valid.

A valid string must meet:

The left parenthesis must be closed with the same type of right parenthesis.
The opening parenthesis must be closed in the correct order.

Seeing this kind of matching problem, the first reaction is definitely to use the stack to achieve it, so I found a treasure class in java: ArrayDeque (double-ended queue)
It is said that the performance of this buddy is better than Listed, and you know that it is double by listening to the name. End, double-ended, then it can be used on the queue, or on the stack. It’s too late to meet such a simple and rude container.

Use ArrayDeque to solve this problem:

if(s==null||s.length()==1)return false;
        ArrayDeque<Character> c=new ArrayDeque<Character>();
    	for(int i=0;i<s.length();i++) {
    
    
    		switch (s.charAt(i)) {
    
    
    		case '(':c.push(s.charAt(i));break;
    		case '{':c.push(s.charAt(i));break;
    		case '[':c.push(s.charAt(i));break;
    		case ')':{
    
    
    			if(c.isEmpty()!=true&&c.peekFirst()=='(') {
    
    c.pollFirst();break;}
    			else return false;
    		}
    		case ']':{
    
    
    			if(c.isEmpty()!=true&&'['==c.peekFirst()){
    
    c.pollFirst();break;}
    			else return false;
    		}
    		case '}':{
    
    
    			if(c.isEmpty()!=true&&'{'==c.peekFirst()){
    
    c.pollFirst();break;}
    			else return false;
    		}
    		}
    	}
    	return c.isEmpty();

It's very simple and rude, just push the stack, compare, and pop.
Then there are some small problems when using this at the beginning:
There are many ways to add and obtain this buddy, such as add, addFirst, push, etc., but when you know that this buddy initialized When there are two pointers (head and tail), it is much easier to understand

The directly added add is added to the end, and other methods are similar. The ones without First and Last are the default operations on the tail. It
should be noted that push (push the stack), this method is to insert the element into the beginning of the deque.
So if you use this method to push the stack, then you need to use the first method to get the top element of the stack, or the pop() accompanying this method, pop the head of the deque
but if it is added to the end normally , Then popping uses the Last method to
obtain but not remove. Get, get[First,Last],peek,peek[First,Last],
get and delete (pop) poll, poll[First,Last ],remove,remove[First,Last],
isEmpty The
above are some of the commonly used methods, you can check the jdk document for details, which are very detailed

Guess you like

Origin blog.csdn.net/qq_50646256/article/details/113409999