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)
  • 相关阅读:
    POJ 3258 (NOIP2015 D2T1跳石头)
    POJ 3122 二分
    POJ 3104 二分
    POJ 1995 快速幂
    409. Longest Palindrome
    389. Find the Difference
    381. Insert Delete GetRandom O(1)
    380. Insert Delete GetRandom O(1)
    355. Design Twitter
    347. Top K Frequent Elements (sort map)
  • 原文地址:https://www.cnblogs.com/USTC-ZCC/p/14582439.html
Copyright © 2011-2022 走看看