首页 > 其他 > 详细

20. Valid Parentheses检验括号字符串的有效性

时间:2020-10-25 11:10:13      阅读:35      评论:0      收藏:0      [点我收藏+]

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

 

 

20. Valid Parentheses检验括号字符串的有效性

原文:https://www.cnblogs.com/immiao0319/p/13871778.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!