0
点赞
收藏
分享

微信扫一扫

BM44 有效括号序列

静悠 2022-03-11 阅读 71

描述

给出一个仅包含字符’(’,’)’,’{’,’}’,’[‘和’]’,的字符串,判断给出的字符串是否是合法的括号序列
括号必须以正确的顺序关闭,"()“和”()[]{}“都是合法的括号序列,但”(]“和”([)]"不合法。
数据范围:字符串长度0≤n≤10000
要求:空间复杂度O(n),时间复杂度O(n)

示例1
输入:"["
返回值:false

示例2
输入:"[]"
返回值:true

代码

class Solution {
public:
    /**
     * 
     * @param s string字符串 
     * @return bool布尔型
     */
    bool isValid(string s) {
        // write code here
        stack<char> st;
        char ch;
        for(int i=0;i<s.length();i++){
            if(s[i]=='('||s[i]=='['||s[i]=='{')
                st.push(s[i]);
            if(s[i]==')'){
                if(st.size()==0)
                    return false;
                ch=st.top();
                st.pop();
                if(ch!='(')
                    return false;
            }else if(s[i]==']'){
                if(st.size()==0)
                    return false;
                ch=st.top();
                st.pop();
                if(ch!='[')
                    return false;
            }else if(s[i]=='}'){
                if(st.size()==0)
                    return false;
                ch=st.top();
                st.pop();
                if(ch!='{')
                    return false;
            }else{}
        }
        if(!st.empty())
            return false;
        return true;
    }
};
举报

相关推荐

0 条评论