19湖南多校第五场

G、 Generalized German Quotation

theme:就是简单的括号匹配问题

solution:对于一般的()、{}、[]问题可以考虑用+/-1等表示左右括号,则每次判断前缀和是否>=0与最终是否为0即可。

但这题<,>都可以作为左括号。括号匹配问题用栈一定能解。

将字符串依次入栈:若栈为空,则进栈;若栈顶与该字符为一对,则凑成一对,栈顶出栈,否则字符入栈。

#include<bits/stdc++.h>
using namespace std;

char c[300];
int a[300];
char b[300];

bool judge(int n)
{
    stack<int>s;
    int cnt=0;
    for(int i=0;i<n;++i)
    {
        if(s.empty())
            s.push(a[i]),b[cnt++]='[';
        else
        {
            if(s.top()==a[i])
                s.push(a[i]),b[cnt++]='[';
            else
                s.pop(),b[cnt++]=']';
        }
    }
    b[cnt]='\0';
    if(s.empty())
        return true;
    else
        return false;
}

int main()
{
    scanf("%s",c);
    int l=strlen(c);
    if(l%2)
    {
        printf("Keine Loesung\n");
        return 0;
    }
    for(int i=0;i<l;i+=2)
        if(c[i]=='>')
            a[i/2]=1;
        else
            a[i/2]=0;
    if(!judge(l/2))
        printf("Keine Loesung\n");
    else
        printf("%s\n",b);
}

猜你喜欢

转载自blog.csdn.net/wangqianqianya/article/details/89460839
今日推荐