Skip to content

11019: 【原1019】括号匹配

题目

题目描述

author: 梁晨锦 原OJ链接:https://acm.sjtu.edu.cn/OnlineJudge-old/problem/1019

Description

给定一串由左小括号,即“(”,和右小括号“)”组成的串,判断其是否匹配。

判断其合法的标准为即为数学等式中括号匹配的标准。

Input Format

第1行:N, \( 0 < N \leq 50 \);

第2至N + 1行,一个括号串,保证串的长度不超过100。

Output Format

共N行,若第i个串匹配,为“YES”,否则为“NO”。

Sample Input

3
(())
(()
)(

Sample Output

YES
NO
NO

FineArtz's solution

/* 括号匹配 */
#include <iostream>
#include <sstream>
using namespace std;

int main(){
    int n;
    cin >> n;
    while (n--){
        string s;
        cin >> s;
        istringstream iss(s);
        char ch;
        bool flag = 1;
        int left = 0;
        while (iss >> ch){
            if (ch == '(') ++left;
            else if (ch == ')') --left;
            if (left < 0){
                cout << "NO" << endl;
                flag = 0;
                break;
            }
        }
        if (flag){
            if (left == 0) cout << "YES" << endl;
            else cout << "NO" << endl;
        }
    }
    return 0;
}

ligongzzz's solution

#include "iostream"
#include "cstdio"
#include "cstring"
#include "stack"
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    int n;
    cin >> n;
    for (int i = 0; i < n; ++i) {
        stack<char> stack_data;
        char temp[109];
        cin >> temp;
        int length = strlen(temp);
        for (int j = 0; j < length; ++j) {
            if (temp[j] == '(')
                stack_data.push('(');
            else if (!stack_data.empty() && stack_data.top() == '(')
                stack_data.pop();
            else
                stack_data.push(')');
        }
        if (stack_data.empty())
            cout << "YES" << "\n";
        else
            cout << "NO" << "\n";
    }

    return 0;
}

yyong119's solution

#include <iostream>
#include <cstring>
int n,i,num;
char a[100];
bool p;
int main(){
    using namespace std;
    cin>>n;
    for (int k=1; k<=n; k++){
        cin>>a; p=true; num=0;
        for (i=0; i<=strlen(a)-1; i++){
            if (a[i]=='(') num++;else num--;
            if (num<0){p=false; break;}
        }
        if ((p)&&(num==0)) cout<<"YES"<<endl;else cout<<"NO"<<endl;
    }
    return 0;
}