Check that the bracket in the input string is matched.The brackets include {,},[,],(,).
Input
The first line is an integer , namely N,which is the number of test cases . The following N lines, each line is a string no longer than 100 characters.
Output
First line of Output is an integer, namely N. number of test cases The following N lines, each line is a string of length not exceeding 100.
It is a simple and easy program,that we can just traverse the numbers and push the left brackets into a stack,when we run into the right brackets, have a comparison with the top element in the stack.Meanwhie,if the bracket is matched to the top element,then pop the top element, otherwise, continue to traverse. After the traverse, if the stackis empty, the case is matched.
code for the question(Hope make you some help)
/*@csdn_cinderella wrote at 2016.9.21 22:29*/
nclude<iostream>
#include<string>
#include<stack>
using namespace std;
int main() {
int n;
cin >> n;
while (n--) {
string str;
stack<char> temp;
cin >> str;
int size = str.length();
for (int i = 0; i < size; i++) {
if (str[i] == '(' || str[i] == '{' || str[i] == '[') {
temp.push(str[i]);
} else if (str[i] == ')') {
if (temp.empty()) {
temp.push(str[i]);
} else {
if (temp.top() == '(') {
temp.pop();
} else {
temp.push(str[i]);
}
}
} else if (str[i] == '}') {
if (temp.empty()) {
temp.push(str[i]);
} else {
if (temp.top() == '{') {
temp.pop();
} else {
temp.push(str[i]);
}
}
} else if (str[i] == ']') {
if (temp.empty()) {
temp.push(str[i]);
} else {
if (temp.top() == '[') {
temp.pop();
} else {
temp.push(str[i]);
}
}
}
}
if (temp.empty()) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
}
}
括号匹配检查
本文介绍了一个简单的程序设计问题——括号匹配检查。该程序通过遍历输入字符串中的括号,并利用栈来判断括号是否正确配对。文章提供了完整的C++代码实现,包括输入输出流程及核心逻辑。
2878

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



