原题链接:https://leetcode.com/problems/valid-parentheses/
Description
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> A;
size_t n = s.length();
for (size_t i = 0; i < n; i++) {
char &ch = s[i];
if (ch == '(' || ch == '{' || ch == '[') {
A.push(ch);
continue;
}
if (ch == ')') {
if (!A.size()) return false;
if (A.top() == '(') A.pop();
else A.push(ch);
}
if (ch == '}') {
if (!A.size()) return false;
if (A.top() == '{') A.pop();
else A.push(ch);
}
if (ch == ']') {
if (!A.size()) return false;
if (A.top() == '[') A.pop();
else A.push(ch);
}
}
return !A.size();
}
};
本文介绍了一种使用栈数据结构解决括号匹配问题的方法,包括算法原理、代码实现及验证过程。
786

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



