LeetCode 20. 有效的括號

wydxry發表於2020-12-26
class Solution {
public:
    //判斷左右括號是否配對
    bool match(char a, char b) {
        if (a == '(' && b == ')' ||
            a == '[' && b == ']' ||
            a == '{' && b == '}')
            return true;
        return false;
    }

    inline bool isLeft(char c) {
        if (c == '(' || c == '[' || c == '{')   return true;
        return false;
    }

    bool isValid(string s) {
        stack<char> chs;
        for (int i = 0; i < s.length(); i++) {
            if (isLeft(s[i])) {
                chs.push(s[i]);
            }
            else {
                if (!chs.empty()) {
                    char tmp = chs.top();
                    if (!match(tmp, s[i]))
                        return false;
                    chs.pop();
                }
                else
                    return false;
            }
        }
        if (!chs.empty())   return false;
        return true;
    }
};

相關文章