20.有效的括号

题目描述
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
示例

输入: "()"
输出: true
输入: "()[]{}"
输出: true
输入: "(]"
输出: false
输入: "([)]"
输出: false
输入: "{[]}"
输出: true
输入: "("
输出: false
输入: "(("
输出: false

思路
用栈来实现,

  • 扫描字符串,遇到左括号,将对应的右括号压入栈
    • 遇到右括号就从栈顶弹出元素进行匹配,不一样返回false
    • 如果栈为空,意味着只有右括号没有左括号,返回false
  • 如果括号全部匹配的话,最后栈应该为空,即以栈空为是否匹配的标准,栈空则返回true,否则false。

代码
java

class Solution {
    public boolean isValid(String s) {

        Stack<Character> sta = new Stack<>();    
        for (char c : s.toCharArray()) {
            if (c == '('){
                sta.push(')');
            } else if (c == '[') {
                sta.push(']');
            } else if (c == '{') {
                sta.push('}');
            } else if (sta.isEmpty() || sta.pop() != c) {
                return false;
            }
        }
        return sta.isEmpty();
    }
}
class Solution {
    public boolean isValid(String s) {
        Stack<Integer> sta = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            int index = "()[]{}".indexOf(s.substring(i, i+1));
            if (index % 2 == 1) {
                if (sta.isEmpty() || sta.pop() != index - 1) {
                    return false;
                }
            } else {
                sta.push(index);
            }
        }
        return sta.isEmpty();
    }
}

python

class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        dic = {"{":"}", "(":")", "[":"]"}
        for char in s:
            if char in dic.keys():
                stack.append(dic[char])
            elif (stack == [] or stack.pop() != char):
                return False
        return stack == []
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值