LeetCode 20. Valid Parentheses

问题描述

  • Given a string 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.
    • Note that an empty string is also considered valid.
  • Example :

Input: “()”
Output: true
Input: “()[]{}”
Output: true
Input: “(]”
Output: false
Input: “([)]”
Output: false
Input: “{[]}”
Output: true

问题分析

  • 利用栈来匹配左右括号
  • 方法1 : 如果当前字符是左括号则入栈,如果是右括号,若当前栈为空,返回false。否则检查当前弹栈元素是否能匹配,若不能,则返回false。若能,则继续检查下一字符。若检查完毕,栈为空说明全部匹配完成,否则,说明左括号比右括号多,返回false
  • 方法2,若遇到左括号,则将它对应的右括号入栈,遇到右括号,若栈空,则为false.否则,进一步检查出栈元素是否等于当前右括号,若不等,则为false。若等,则继续检查下一字符。若检查完毕,栈为空说明全部匹配完成,否则,说明左括号比右括号多,返回false

代码实现

  • 方法1:
    public boolean isValid(String s) {
        if (s == null) {
            return true;
        }
        char[] chs = s.toCharArray();
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < chs.length; i++) {
            char ch = chs[i];
            if (ch == '(' || ch == '[' || ch == '{') {
                stack.push(ch);
            }else {
                if (ch == ')') {
                    //注意判空,防止 ({}))
                    if (stack.isEmpty() || stack.pop() != '('){
                        return false;
                    }
                }else if (ch == ']') {
                    if (stack.isEmpty() ||stack.pop() != '['){
                        return false;
                    }
                }else if (ch == '}') {
                    if (stack.isEmpty() ||stack.pop() != '{'){
                        return false;
                    }
                }else {
                    return false;
                }
            }
        }
        //防止左括号个数多于右括号这种情况 :((({}))
        return stack.isEmpty();
    }
  • 方法2:
    public boolean isValid(String s) {
        if (s == null) {
            return true;
        }
        Stack<Character> stack = new Stack<>();
        for (char ch : s.toCharArray()) {
            switch (ch) {
                case '(' : stack.push(')'); break;
                case '[' : stack.push(']'); break;
                case '{' : stack.push('}'); break;
                case ')' :
                case ']' :
                case '}' : 
                    if (stack.isEmpty() || stack.pop() != ch) {
                        return false;
                    }
            }
        }
        return stack.isEmpty();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值