20. Valid Parentheses


做题历程:

  1. 本题应该做了不止两遍了,这次用时8分钟独立解出

本题思路就是用Stack,做的次数太多了,就不多说了,直接上代码,代码如下:

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

results matching ""

    No results matching ""