Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
如下:
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for(auto c : s){
if(c == '(')
st.push(')');
else if(c == '[')
st.push(']');
else if(c == '{')
st.push('}');
else {
if(st.empty() || st.top() != c)
return false;
st.pop();
}
}
return st.empty();
}
};
本文介绍了一种使用栈数据结构来验证包含括号的字符串是否有效的方法。通过将左括号压入栈中,并在遇到右括号时检查栈顶元素是否为对应的左括号来实现。该方法适用于括号配对问题,如'()'和'()[]{}

被折叠的 条评论
为什么被折叠?



