题解:P14172 【MX-X23-T2】括号串

· · 题解

这是一道结论题

首先,一个括号串想要合法,对于每一对括号,一定是左括号在前,右括号在后(而且长度必为偶数),所以,我们不难得出结论,对于任意的 1<=i<=n ,合法括号串 s 中 1...i 的子串都有左括号数量大于等于右括号,所以我们设个 cnt,遇到左括号就 +1,遇到右括号就 -1,如果 cnt 变负数了就不合法。而且最后 cnt 一定要为零。

那么特殊情况怎么处理?题目说能且只能改一对 ")(" ,那么,我们不难发现,当首次出现 ")("时,即遍历到 ")" 时,cnt 定为 -1,同时,想要合法,它的下一个一定要为 "(" ,使 cnt 清零,换句话说,即在遍历时只能只能遍历到一次负数,所以当遍历到负数时,如果以前有过负数,就为不合法。

以下为我的 AC 代码

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int T;
    cin>>T;
    for(int u=0;u<T;u++)
    {
        int n;
        string s;
        cin>>n>>s;
        if(s.length()%2)
        {
            cout<<"No"<<endl;
            continue;
        }
        int cnt=0;
        int c=0;
        for(int x=0;x<n;x++)
        {
            if(s[x]=='(')
            {
                cnt++;
            }
            else
            {
                cnt--;
            }
            if(cnt<0)
            {
                if(c)
                {
                    break;
                }
                c++;
            }
        }
        if(cnt==0&&c<2)
        {
            cout<<"Yes"<<endl;
        }
        else
        {
            cout<<"No"<<endl;
        }
    }
}