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.

 

Example 1:

Input: s = "()"
Output: true

Example 2:

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

Example 3:

Input: s = "(]"
Output: false

Example 4:

Input: s = "([)]"
Output: false

Example 5:

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

这种带技巧的题,真的忘了

思路是:先全部push进去,再pop


stack.pop() == null会出异常,所以应该是stack.isEmpty()


最后检查一下stack是否为空

 

class Solution {
    public boolean isValid(String s) {
        //cc
        if (s == null || s == "")
            return true;
        
        //新建一个stack,遍历s中的每一个元素
        Stack<Character> stack = new Stack<Character>();
        
        //返回
        for (char c : s.toCharArray()) {
            if (c == '(') {
                stack.push(')');
            } else if (c == '{') {
                stack.push('}');
            } else if (c == '[') {
                stack.push(']');
            } else {
                if (stack.pop() == null || stack.pop() != c)
                    return false;
            }
        }
        
        return stack.isEmpty();
    }
}
View Code

 

 
posted @ 2020-10-25 00:39  苗妙苗  阅读(85)  评论(0编辑  收藏  举报