• Leetcode valid-parentheses(判断括号 栈)


    题目描述

    给出一个仅包含字符'(',')','{','}','['和']',的字符串,判断给出的字符串是否是合法的括号序列
    括号必须以正确的顺序关闭,"()"和"()[]{}"都是合法的括号序列,但"(]"和"([)]"不合法。

    Given a string containing just the characters'(',')','{','}','['and']', determine if the input string is valid.

    The brackets must close in the correct order,"()"and"()[]{}"are all valid but"(]"and"([)]"are not.

     
    思路:利用栈,如果是左括号,则放入右括号,如果是右括号,则跟最近的左括号对比,也就是跟栈顶对比,配对则继续,不配对或者栈空了,则不合法。
    class Solution {
    public:
        bool isValid(string s) {
            stack<char> st;
            int n=s.size();
            if(n%2!=0)
                return false;
            for(int i=0;i<n;++i)
            {
                if(s[i]=='(')
                    st.push(')');
                else if(s[i]=='[')
                    st.push(']');
                else if(s[i]=='{')
                    st.push('}');
                else if(st.empty()||st.top()!=s[i])
                    return false;
                else
                    st.pop();
            }
            if(st.empty()) return true;
            return false;
        }
    };
  • 相关阅读:
    SQL 语言入门
    [转载]Sql Server 中的Login,Schema,User,Role之间的关系
    稀疏矩阵运算
    特征缩放的几种方法
    dp解出栈序列数
    神经网络解决多分类问题例:数字识别
    多分类例题
    fminunc 函数的用法
    二分类
    特征归一化、特征映射、正则化
  • 原文地址:https://www.cnblogs.com/zl1991/p/12783638.html
Copyright © 2020-2023  润新知