20. 有效的括号
-
解题思路:括号匹配问题,优先想到栈。
-
代码
class Solution { public: bool isValid(string s) { stack<char> st; for (auto &ch : s) { // 如果是右括号,那么必须得有一个相匹配的左括号 if (ch == ')') { if (st.empty() || st.top() != '(') { return false; } st.pop(); } else if(ch == '}') { if (st.empty() || st.top() != '{') { return false; } st.pop(); } else if (ch == ']') { if (st.empty() || st.top() != '[') { return false; } st.pop(); } else { // 如果是左括号,那么直接压入栈 st.push(ch); } } // 别忘记,栈要空,否则就是左括号太多了 return st.empty(); } };

浙公网安备 33010602011771号