题解 | #合法括号序列判断#
合法括号序列判断
https://www.nowcoder.com/practice/d8acfa0619814b2d98f12c071aef20d4
合法括号判断
/*
2022年09月21日 11:43:09
栈中存放左括号,当遇到右括号之后,
检查栈中是否有左括号,如果有则出栈,如果没有,则说明不匹配。
最后判断栈是否为空
*/
class Parenthesis {
public:
bool chkParenthesis(string A, int n) {
stack<char> st;
for (int i = 0; i < n; ++i) {
if (A[i] == '(')
st.push(A[i]);
else if (A[i] == ')')
if(st.empty() || st.top() != '(')
return false;
else
st.pop();
else
return false;
}
return st.empty();
}
};

