7-6 Legality of stack operations (20 points)

7-6 Legality of stack operations (20 points)

Suppose the push and pop operations are denoted by and , respectively S. XIf an operation is performed on an empty stack according to a sequence consisting only of Sand 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 Sand Xsequence, 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 Sand . XThe sequence is guaranteed not to be empty and not to exceed 100 in length.

Output format:

For each sequence, print on one line YESif the sequence is a valid stack manipulation sequence, or NOif 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;
}

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325375877&siteId=291194637