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) {
string left = "([{";
string right = ")]}";
stack<char> p;
for (auto i : s) {
if (left.find(i) != string::npos) {
p.push(i);
} else {
if (p.empty() || p.top() != left[right.find(i)]) {
return false;
}
p.pop();
}
}
return p.empty();
}
};
本文介绍了一种使用栈数据结构来验证括号是否正确配对的方法。对于包含'(',')','[',']','{','}
926

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



