zoukankan      html  css  js  c++  java
  • 20. 有效的括号

    题目:给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。有效字符串需满足:左括号必须用相同类型的右括号闭合。左括号必须以正确的顺序闭合。

    示例 1:

    输入:s = "()"
    输出:true
    示例 2:

    输入:s = "()[]{}"
    输出:true
    示例 3:

    输入:s = "(]"
    输出:false

    1.原创

    class Solution {
    public:
        bool isValid(string s) {
            stack<char> stack_tmp;
            for (char i:s){
                if (i=='(' || i=='{' || i=='[')
                    stack_tmp.push(i);
                else
                {
                    if (
                        (i==')'&& !stack_tmp.empty() && stack_tmp.top()=='(') 
                        || (i=='}'&& !stack_tmp.empty() && stack_tmp.top()=='{')  
                        || (i==']'&& !stack_tmp.empty() && stack_tmp.top()=='[')
                        )
                        stack_tmp.pop();
                    else 
                        stack_tmp.push(i);
                }
            }
            if (stack_tmp.empty())
                return true;
            else    
                return false;
        }
    };

    2.题解

    class Solution {
    public:
        bool isValid(string s) {
            int n = s.size();
            if (n % 2 == 1) {
                return false;
            }
    
            unordered_map<char, char> pairs = {
                {')', '('},
                {']', '['},
                {'}', '{'}
            };
            stack<char> stk;
            for (char ch: s) {
                if (pairs.count(ch)) {
                    if (stk.empty() || stk.top() != pairs[ch]) {
                        return false;
                    }
                    stk.pop();
                }
                else {
                    stk.push(ch);
                }
            }
            return stk.empty();
        }
    };
    
    作者:LeetCode-Solution
    链接:https://leetcode-cn.com/problems/valid-parentheses/solution/you-xiao-de-gua-hao-by-leetcode-solution/
    来源:力扣(LeetCode)
  • 相关阅读:
    [JLOI2015] 管道连接
    【知识点】斯坦纳树
    [ZJOI2010] 网络扩容
    【知识点】网络流常见模型
    [NOI2009] 植物大战僵尸
    [NOI2007] 货币兑换
    【知识点】分治相关算法
    [NOI2005] 月下柠檬树
    [HNOI2012] 射箭
    [SDOI2014] 向量集
  • 原文地址:https://www.cnblogs.com/USTC-ZCC/p/14582439.html
Copyright © 2011-2022 走看看