标签 栈 下的文章

题目链接:有效的括号

给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

  • 左括号必须用相同类型的右括号闭合。
  • 左括号必须以正确的顺序闭合。
  • 每个右括号都有一个对应的相同类型的左括号。

方法一:栈

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