LeeCode (stack) 20_ valid parentheses

LeeCode (stack) 20_ valid parentheses

Title:
Given a string 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.
Note that an empty string can be considered a valid string.

Example 1:

Input: "()"
Output: true
Example 2:

Input: "()[]{}"
Output: true
Example 3:

Input: "(]"
Output: false
Example 4:

Input: "([)]"
Output: false
Example 5:

Input: "{[]}"
Output: true

Source: LeetCode
Link: https://leetcode-cn.com/problems/valid-parentheses
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Problem-solving ideas:

  1. First judge whether the string length is an even number, and if it is an odd number, it is judged as invalid.
  2. Create a Map with the right parenthesis as the key and the left parenthesis as the value
  3. Use the Deque class to create a stack and implement it with LinkedList (LinkedList inserts and deletes fast; ArrayList random query is fast)
  4. Judge if it is a left parenthesis (such as: (,[,{ ), then push the stack operation; if it is a right parenthesis, judge whether the top of the stack is the corresponding right parenthesis, and if the pairing is successful, pop the top of the stack.
  5. At the end of the loop, it is judged whether there are still matching parentheses in the stack.

Java code:

	public boolean isValid(String s) {
    
    
		int len = s.length();
		if(len%2==1)
			return false;
		Map<Character,Character> map = new HashMap<Character,Character>(){
    
    {
    
    
			put(')','(');
			put(']','[');
			put('}','{');
			
		}};
		
		Deque<Character> stack = new LinkedList<Character>();
		for(int i = 0; i < len; i++){
    
    
			char ch = s.charAt(i);
			if(map.containsKey(ch) ){
    
    
				if(map.get(ch)!=stack.peek())
					return false;
				else
					stack.pop();
			}else{
    
    
				stack.push(ch);
			}
		}
		return stack.isEmpty();
	}

Guess you like

Origin blog.csdn.net/u013456390/article/details/111773357