nyoj 2 bracket matching --Getchar

parentheses problem

Time Limit: 3000 ms | Memory Limit: 65535 KB | Difficulty: 3
 
describe
   Now, there is a sequence of parentheses, please check whether the parentheses are matched.
enter
   Enter a number N (0<N<=100) in the first line, indicating that there are N groups of test data. The following N lines input multiple sets of input data, each set of input data is a string S (the length of S is less than 10000, and S is not an empty string), and the number of test data sets is less than 5 sets. Data guarantee that S only contains four characters "[", "]", "(", ")"
output
  The output of each set of input data occupies one line. If the brackets contained in the string are paired, output Yes, if not, output No.
/**
     Analysis: 1. Use the data structure stack (stack);
              2. If '[' or '(' is encountered, push it to the stack;
              3. If you encounter ']' or ')', judge whether stack.top() is paired with it
              4. It is illegal to enter ']' or ')' into the empty stack
              5. Illegal in other circumstances
**/

C++ code implementation:

#include <iostream>
#include <algorithm>
#include <cstring>
#include <stack>

using namespace std;

int main() {
    int N;
    cin >>N;
    while (N --) {
        stack <char> stackChar;
        string A;
        bool judgeBrack=true;
        cin >>A;

        for (int i=0; i<A.size(); ++i) {
            if (A[i] == '[' || A[i] == '(') {
                stackChar.push(A[i]);
            } else if (stackChar.empty()) {
                judgeBrack = false;
                break;
            } else if (A[i] == ']' && stackChar.top() == '[') {
                stackChar.pop();
            } else if (A[i] == ')' && stackChar.top() == '(') {
                stackChar.pop();
            } else {
                judgeBrack = false;
                break;
            }
        }

        judgeBrack? cout <<"Yes" <<endl: cout<< "No" <<endl;
    }
    return 0;
}

 

Guess you like

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