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 stack
is 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;
}
}
}