leetcode

题目链接

解题思路:
就是对的应用,将左括号入栈,当读入右括号时查询栈顶是否为相对应的左括号。

Code:

#include <iostream>
#include <string>
#include <stack>

using namespace std;


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


int main() {
    Solution solution;
    string string1;
    cin >> string1;
    bool result;
    result = solution.isValid(string1);
    cout << boolalpha << result << endl;
    return 0;
}