LeetCode—— 有效的括号

题目地址:https://leetcode-cn.com/problems/valid-parentheses/

解题思路:栈的操作

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

 

posted @ 2020-08-06 15:11  CCxiao5  阅读(94)  评论(0编辑  收藏  举报