题解 | #有效括号序列#

有效括号序列

https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2

class Solution {
  public:
    bool isValid(string s) {
        // write code here
        stack<char> comp_stack;
        for (char& c : s) {
            if (c == '(' || c == '{' || c == '[') {
                comp_stack.push(c);
                continue;
            }
            if(comp_stack.empty())
                return false;
            char top = comp_stack.top();
            if (top == '(' && c == ')') {
                comp_stack.pop();
                continue;
            }
            if (top == '[' && c == ']') {
                comp_stack.pop();
                continue;
            }
            if (top == '{' && c == '}') {
                comp_stack.pop();
                continue;
            }
            return false;
        }
        return comp_stack.size() == 0 ? true : false;
    }
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务