Respuesta :
Question
You are given a string consisting of parenthesis style characters ( ) [ ] and { }. A string of this type is said to be correct if: (a) It is an empty string. (b) If string A is correct and string B is correct then string AB is correct. (c) If A is correct then (A), [A] and {A} are all correct. You are to write a program that takes as input from the keyboard a series of strings of this type that can be of any length. The first line of input will contain a single integer n telling you how many strings you will be testing. Following that integer will be n lines (each ending in a new line character) that represent the strings you are supposed to test with one string per line. Your program should output Yes if a given string is correct and No otherwise. For example if the user types the following as input 3 ([]) (([{}]))) ([()[]()])() Then your program should give the following output: Yes No Yes You will note that if you do your program correctly there is no prompt for data and the yes and no answers will be interspersed with your input data when you enter it manually. The following would be a more accurate representation of what you see on the screen when you cut and paste the input into your program. 3 ([]) Yes (([{}]))) No ([()[]()])() Yes
The question stopped here -------------------
Answer:
// Program is written in C Programming Language
// Comments are used for explanatory purpose
// Program starts from here
#include<iostream>
#include <cstdio>
#include <stack>
using namespace std;
//Variable Declarations
int count, i; string textline;
// Declare stack for push and pop actions
stack<char> pushpop;
// Main method starts here
int main() {
// The next line accepts integer value through the keyboard from the user
scanf("%d\n", &count);
// Start an iteration
while (count--) {
// Perform push/pop operation depending on the value of pushpop Variable
while pushpop.size() > 0) {
pushpop.pop();
}
// The following reads a string or a line from an input stream.
getline(cin, textline);
// Iterate through size of textline Variable
for (i = 0; i < textline.size(); i++) {
// Perform push/pop operation
if (textline[i] == '(' || textline[i] == '[') {
pushpop.push(textline[i]);
} else if (pushpop.empty()) {
pushpop.push('E');
break;
} else if (textline[i] == ')' && pushpop.top() == '(') {
pushpop.pop();
} else if (textline[i] == ']' && pushpop.top() == '[') {
pushpop.pop();
} else {
pushpop.push('E');
break;
}
}
// End of iteration
// Print yes or no, depending on the calculated size of pushpop Variable
if (pushpop.size() == 0) {
printf("Yes\n");
} else {
printf("No\n");
}
}
return 0;
};