Likou 20—valid brackets

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

A valid string must satisfy: 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.

**Thinking:** First, think of the stack first, because the pop-up of the stack happens to be first-in-last-out, which can facilitate matching. Secondly, you can use map key-value pairs to divide parentheses into pairs. First traverse the string into the stack, then pop the stack and compare it with the hashmap

answer:

class Solution {
    
    
    public boolean isValid(String s) {
    
    
        HashMap<Character, Character> hashMap = new HashMap<>();
        hashMap.put('}', '{');
        hashMap.put(']', '[');
        hashMap.put(')', '(');
        Stack<Character> charStack = new Stack<>();
        
        for (char c : s.toCharArray()) {
    
    
            if (c == '(' || c == '[' || c == '{') {
    
    
                charStack.push(c);
            } else if (charStack.isEmpty() || charStack.pop() != hashMap.get(c)) {
    
    
                return false;
            }
        }
                return charStack.empty();
    }
}

The effect is as follows:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_42898315/article/details/108441189