LeetCode 20. 有效的括号

20. 有效的括号


题目:

LeetCode 20. 有效的括号_第1张图片


  • 题解:

栈(可以在判断栈长度大于剩余长度时直接退出false)


  • 代码:
class Solution20 {
public:
    bool isValid(string s) {
        if (s == "") {
            return true;
        }
        if (s.length() % 2 != 0) {
            return false;
        }
        stack st;
        int i = 0;
        for (const char& ch : s) {
            if (st.empty() || ch == '(' || ch == '[' || ch == '{') {
                st.push(ch);
            } else if ((ch == ')' && st.top() == '(') || (ch == ']' && st.top() == '[') ||
                (ch == '}' && st.top() == '{')) {
                st.pop();
            } else {
                return false;
            }
            i++;
        }
        return true;
    }
};

  • 进阶:

1111. 有效括号的嵌套深度

你可能感兴趣的:(leetcode,栈,c++)