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:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Input: s = "()[]{}"
Output: true

 

方法:

利用栈,左括号入栈,右括号则从栈中取值看是否配对,注意pop时判断是否为空,最后栈为空则有效。

 

public boolean isValid(String s) {
        if (s == null || s.length() % 2 != 0)
            return false;
        Stack<Character> stack = new Stack<>();

        char [] str = s.toCharArray();
        for(char c : str) {
            if (c == '(' || c == '[' || c == '{') {
                stack.push(c);
            } else {
                if (stack.size() == 0) return false;
                Character pair = stack.pop();
                if (c == ')' && pair != '(' ||
                        c == ']' && pair != '[' ||
                        c == '}' && pair != '{')
                    return false;
            }
        }

        if (stack.size() != 0)
            return false;
        return true;
    }

 

参考链接:

https://leetcode.com/problems/valid-parentheses/

https://leetcode-cn.com/problems/valid-parentheses/

posted @ 2020-12-04 11:01  diameter  阅读(113)  评论(0编辑  收藏  举报