题目描述
Valid Parentheses
Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.An input string is valid if:
1.Open brackets must be closed by the same type of brackets.
2.Open brackets must be closed in the correct order.Note that an empty string is also considered valid.
题目大意
括号匹配。
思路分析
简单的栈的应用。
关键代码
bool match(char a, char b) {
if (a == '(') return b == ')';
if (a == '[') return b == ']';
if (a == '{') return b == '}';
return false;
}
bool isValid(string s) {
stack<char> stack1;
int n = s.length();
for (int i = 0; i < n; i++) {
if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
stack1.push(s[i]);
} else if (stack1.empty()) {
return false;
} else {
if (match(stack1.top(), s[i])) {
stack1.pop();
} else {
return false;
}
}
}
if (stack1.empty()) {
return true;
} else {
return false;
}
}
总结
当复习栈吧。
本文详细解析了括号匹配问题的解决思路,通过使用栈的数据结构实现有效的括号验证算法。文章提供了完整的代码示例,并解释了如何判断输入字符串中的括号是否正确配对。
7543

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



