HDU 第三场Parentheses Matching

思路:
按题目会给出一个字符串,呢么我们先将给出的字符串进行匹配,最终剩下没有匹配的字符串,除去’*‘号,最左边的可能就是’)’,最右边的可能就是’(’,为什么说可能,因为可能一边没有,但是也没有匹配。
举个例子:
在这里插入图片描述
首先左右括号不可能区间相交,所以我们只需要记录每个括号的左边或者右边 * 号数量是否够即可,然后对于)取最早出现的 *,取完为止,若*号的数量少于未匹配的一种括号数量显然是不匹配的,我们只需要对两种括号进行检查即可,最后对原字符串赋值即可。

参考代码:

#include <cstdio>
#include <algorithm>
#include <iostream>
#include <vector>
#include <map>
#include <queue>
#include <stack>
#include <set>
#include <ctime>
#include <cstring>
#include <cstdlib>
#include <math.h>
using namespace std;
typedef long long ll;
const int N = 1e3 + 5;
const int maxn = 3e5 + 5;
map<ll, ll> mp;
int pre[maxn], vis[30];
char dp[maxn];
vector<ll> vec;
typedef pair<char, int> p;
stack<p> q;
ll a[maxn], sum[maxn];
char pc[maxn];
char s[maxn];
int main()
{
    // ios::sync_with_stdio(false);
    // cin.tie(0);
    int t;
    cin >> t;
    while (t--)
    {
        while (!q.empty())
            q.pop();
        scanf("%s", s + 1);
        int n = strlen(s + 1);
        for (int i = 1; i <= n; i++) //得到未匹配的字符串pc
        {
            pc[i] = s[i];
            if (s[i] == '(')
                q.push(p(s[i], i));
            else if (s[i] != '*')
            {
                if (!q.empty())
                    pc[q.top().second] = pc[i] = '!', q.pop();
            }
        }
        bool fla = false;
        int lp = 0, rp = 0, k = n + 1;
        for (int i = 1; i <= n; i++)//检查)的数量并查看是否可以构造出合格的括号
        {
            if (pc[i] == '*')
                lp++;
            if (pc[i] == ')')
            {
                if (!lp)
                {
                    fla = true;
                    break;
                }
                rp++, lp--;
            }
            if (pc[i] == '(')
            {
                k = i;
                break;
            }
        }
        for (int i = 1; i <= n; i++)//若可以成功最早出现的*变为(,为匹配的)--
        {
            if (pc[i] == '*' && rp)
                s[i] = '(', rp--;
        }
        lp = 0, rp = 0;//以上同理
        for (int i = n; i >= k; i--)
        {
            if (pc[i] == '*')
                rp++;
            if (pc[i] == '(')
            {
                if (!rp)
                {
                    fla = true;
                    break;
                }
                rp--, lp++;
            }
        }
        for (int i = n; i >= k; i--)
        {
            if (pc[i] == '*' && lp)
                s[i] = ')', lp--;
        }
        if (fla)
            puts("No solution!");
        else
        {
            for (int i = 1; i <= n; i++)
            {
                if (s[i] != '*')
                    putchar(s[i]);
            }
            puts("");
        }
    }
}

猜你喜欢

转载自blog.csdn.net/yangzijiangac/article/details/107657041
今日推荐