I also want to brush the effective brackets of the force button 05 (ctf has been dragged for a few days)

Includes only a given '(', ')', '{', '}', '[', ']'string, determines whether the string is valid.
A valid string must meet:

  1. The left parenthesis must be closed with the same type of right parenthesis.
  2. 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
public boolean isValid(String s) {
    
    
        Deque<Character> stack = new ArrayDeque<>();//一种数据结构
        for (int i = 0; i < s.length(); i++) {
    
    
            if (s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[') {
    
    
                stack.push(s.charAt(i));
            } else {
    
    
                if (stack.isEmpty()) {
    
    
                    return false;
                } else {
    
    
                    if (stack.peek() == '(' && s.charAt(i) != ')') {
    
    
                        return false;//返回栈顶元素
                    } else if (stack.peek() == '{' && s.charAt(i) != '}') {
    
    
                        return false;
                    } else if (stack.peek() == '[' && s.charAt(i) != ']') {
    
    
                        return false;
                    }
                    stack.pop();
                }
            }
        }
        return stack.isEmpty();
 }

Guess you like

Origin blog.csdn.net/qq_45864370/article/details/108702093