7-6 Legality of stack operations (20 points)
Suppose the push and pop operations are denoted by and , respectively S
. X
If an operation is performed on an empty stack according to a sequence consisting only of S
and X
, the corresponding operations are feasible (for example, the stack is empty when there is no deletion), and the final state is also the stack empty, then the sequence is called a legal stack operation sequence. Please write a program, input S
and X
sequence, to determine whether the sequence is legal.
Input format:
The first line of input gives two positive integers N and M, where N is the number of sequences to be tested and M ( ≤ 5 0) is the maximum capacity of the stack. Next N lines, each of which is given a sequence consisting of only S
and . X
The sequence is guaranteed not to be empty and not to exceed 100 in length.
Output format:
For each sequence, print on one line YES
if the sequence is a valid stack manipulation sequence, or NO
if it is not.
Input sample:
4 10
SSSXXSXXSX
SSSXXSXXS
SSSSSSSSSSXSSXXXXXXXXXXX
SSSXXSXXX
Sample output:
YES NO NO NO
Idea: No one will build a stack, right?
#include<string> #include<iostream> using namespace std; int main() { string str; int n, m; cin >> n >> m; getchar(); while (n--){ int cnt = 0; str.clear(); getline (cin, str); int flag = 0; for (int i = 0; i < str.length(); i++){ if (str[i] == 'X')cnt--; if (str[i] == 'S')cnt++; if (cnt < 0 || cnt>m){ flag = 1; break; } } if (cnt != 0)flag = 1; if (cnt == 0)cout << "YES" << endl; else cout << "NO" << endl; } return 0; }