NYOJ 括号配对问题

时间限制:3000 ms  |  内存限制:65535 KB

难度:3

输入

第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有"[", "]", "(", ")" 四种字符

输出

每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes,如果不配对则输出No

样例输入

3
[(])
(])
([[]()])

样例输出

No
No
Yes

#include <iostream>
#include <cstdio>
#include <vector>
#include <string>

using namespace std;

int main(int argc, char const *argv[]) {
    //N组数据
    int N;

    scanf("%d",&N);
    //用于存储每一组的答案
    vector<string> q;

    //循环N组
    for(int i = 0;i < N;i++){
        string str;
        cin >> str;

        string::iterator front = str.begin();
        while(front != str.end()){
            //标志
            int w = 0;
            //ASCALL码 '(' => 40   ')' => 41  '[' => 91  ']' => 93
            if(*front + 1 == *(front + 1) || *front + 2 == *(front + 1)){
                // cout << *front << " " << *(front+1) << "\n" ;
                //删除配对的一组
                str.erase(front,front + 2);
                //标志删除后
                w = 1;
            }
            //删除后从头开始 重新遍历
            if(w == 1)front = str.begin();
            //否则继续遍历
            else front++;
        }
        //当全都删除后代表 都能配对成功
        if(str.empty())q.push_back("Yes");
        else q.push_back("No");
    }

    for(vector<string>::iterator i = q.begin();i != q.end();i++)
        cout << *i << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/WX_1218639030/article/details/83996757