[NYOJ] [v1-2] Bracket Matching Problem

Problem Description

括号配对问题
Time limit: 3000 msMemory limit: 128 MB

Description

Given a line of bracket sequence, check whether the brackets in this line are matched.

Input

The first line contains a number N (0<N<=100), indicating there are N groups of test data. The following N lines contain multiple groups of input data, each group is a string S (the length of S is less than 10000, and S is not an empty string); the number of test data groups is fewer than 5. The data guarantees that S contains only four characters: “[”, “]”, “(”, “)”.

Output

Each group of input data produces one line of output. If the brackets contained in the string are matched, output Yes; if not matched, output

Sample Input

1
2
3
4
3
[(])
(])
([[]()])

Sample Output

1
2
3
No
No
Yes

Source

Bracket Matching Problem - NYOJ

Problem Analysis

Use a stack to check whether they correspond

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include<stdio.h>
#include<string.h>
#include<stack>
using namespace std;
char s[10200];
stack<char>q;
bool judge(char a,char b) {
    if(a=='('&&b==')')
        return false;
    if(a=='['&&b==']')
        return false;
    return true;
}
int main() {
    int T;
    scanf("%d",&T);
    while(T--) {
        scanf("%s",s);
        int l=strlen(s);
        bool flag=true;
        while(!q.empty())
            q.pop();
        for(int i=0; i<l; i++) {
            if(!flag)
                continue;
            if(s[i]=='['||s[i]=='(')
                q.push(s[i]);
            else {
                if(q.empty()||judge(q.top(),s[i]))
                    flag=false;
                else
                    q.pop();
            }
        }
        printf("%s\n",flag?"Yes":"No");
    }
    return 0;
}
This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...