*20. Valid Parentheses[Easy]

20. Valid Parentheses

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Every close bracket has a corresponding open bracket of the same type.

Constraints:

  • 1 <= s.length <= 10^4
  • s consists of parentheses only '()[]{}'.

Example

Input: s = "()"
Output: true

思路

  • 先把题目里给定的三组用Map存起来,作为字典
  • 利用栈的先进后出的特性,如果是开始符就进栈,结束符的话,就出栈一个元素来和它比较是否为一对,是一对的话就相当于消除了一对,以此类推

题解

    public boolean isValid(String s) {
        char[] data = s.toCharArray();
        Stack<Character> stack = new Stack<>();
        HashMap<Character, Character> dict = new HashMap<>();
        dict.put('}', '{');
        dict.put(')', '(');
        dict.put(']', '[');

        for (char val : data) {
            // 判断当前字符是否结束符
            if (dict.containsKey(val)) {
                // 是结束符就要先看一下当前栈里是否有元素,如果没有,就代表这个结束符是首位,那直接false
                if (stack.isEmpty())
                    return false;
                // 如果栈中有元素,那就看栈中这个元素是否和当前元素对应,如果不等于,那就是不对应,也返回false
                if (!stack.pop().equals(dict.get(val)))
                    return false;
            } else
                // 如果不是结束符,就入栈
                stack.push(val);
        }
        // 如果到最后还剩下元素在栈内,就代表还有没有消除的,返回false,否则就是true
        return stack.isEmpty();
    }
posted @ 2023-01-29 17:02  AaronTanooo  阅读(19)  评论(0)    收藏  举报