- 采用栈;
- 遍历字符,如果为左括号,则将对应右括号放入栈内;
- 栈为空,说明只有右括号,返回false;
- 当前字符与栈顶元素不同,返回false,否则,弹出栈顶元素;
- 最后,判断栈是否为空。
class Solution {
public:
/**
*
* @param s string字符串
* @return bool布尔型
*/
bool isValid(string s) {
// write code here
stack<char> st;
for (char ch : s) {
if (ch == '(') {
st.push(')');
}
else if (ch == '{') {
st.push('}');
}
else if (ch == '[') {
st.push(']');
}
else if (st.empty()) {
return false;
}
else if (ch != st.top()) {
return false;
}
else {
st.pop();
}
}
return st.empty();
}
};