
class Solution {
public:
bool isValid(string s) {
stack<char> helper;
int N = s.length();
for(int i =0; i<N; i++){
if (s[i] == '{' || s[i] == '(' ||s[i] == '[') helper.push(s[i]);
else{
if (helper.empty()) return false;
if (s[i] == ')') if (helper.top() != '(') return false;
if (s[i] == ']') if (helper.top() != '[') return false;
if (s[i] == '}') if (helper.top() != '{') return false;
helper.pop();
}
}
if (!helper.empty()) return false;
return true;
}
};

本文介绍了一种使用栈数据结构实现的C++算法,用于判断字符串中的括号是否正确匹配。通过遍历字符串,遇到开括号将其压入栈中,遇到闭括号则检查栈顶元素是否为对应的开括号,以此来确保括号的正确闭合。
338

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



