题解 | #有效括号序列#
有效括号序列
https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2
class Solution { public: /** * * @param s string字符串 * @return bool布尔型 */ bool isValid(string s) { if(s.empty()) return true; // 如果字符串为空,直接返回true stack<char> st; for(auto it : s){ // 遍历字符串 // 如果it为左括号,则将对应的右括号压入栈中 if(it == '(') st.push(')'); else if(it == '[') st.push(']'); else if(it == '{') st.push('}'); // 如果it为右括号 else{ if(st.empty() || it != st.top()) return false; // 如果it为右括号,但是栈中元素为空或者不等于栈顶元素,则括号序列不合法,直接返回false else st.pop(); // 如果it为右括号,且等于栈顶元素,说明跟栈顶括号配对成功,需要出栈 } } // 循环结束,如果栈为空,括号序列合法 if(st.empty()) return true; // 否则,不合法 return false; } };