Let's Line Up Parentheses(模拟+栈)

一道训练赛上的题目,当时写了一个多小时才写出来,先看题面:

Given a string of parentheses, you are to use the vertical bar (’|’) and underscore (’_’) characters to connect the matching parentheses.

The Input:
The first input line will be a positive integer n,indicating the number of strings to be processed. Each of the following n input lines contains a string. Each string will be at most 30 characters and will contain only the open and close parentheses and spaces, i.e., no other characters. There will be at least one parenthesis in each input string.

The Output:
Print a heading for each input string. Then, print the string with exactly one space between parentheses. If there is any mismatched parentheses in the string, print the message “Parentheses do not match!” Otherwise, use the vertical bar and underscore characters to draw lines between matching parentheses. Each line must be at least one vertical bar in depth but no line should be deeper than it needs to be. Leave a blank line after the output for each data set. Follow the format illustrated in Sample Output.
Let's Line Up Parentheses(模拟+栈)_第1张图片

题意翻译:

就是给出n个由括号和空格组成的字符串,对每个字符串进行操作,把每个对应的括号连起来,如果括号不匹配则输出那句话。由于样例直接复制会导致显示问题,我就截图了。

大致思路:

利用栈判断一下括号是否匹配,如果不匹配则直接输出然后continue到下一行字符串,如果匹配则对括号进行连线,首先把字符串中多余的空格去掉,然后讲括号按照原顺序输出一遍并且括号与括号之间要有空格,然后开始进行连线,连线的时候,把离得最近的匹配的括号连上,如果两个匹配的括号之间有其它匹配的括号,则这两个括号之间暂时先不连,在下一行或者更远的地方连,每连接两个括号,就把他更新为空格,循环进行即可。

下面是AC代码:

#include 
using namespace std;
stackaaa;//定义一个栈用于判断括号是否正确匹配
bool F(char a[],int len)//检测括号是否匹配的函数,匹配则返回真
{
    for(int i=0;i &s){//用于清空栈的函数,因为是多行输入,所以每次判断之前要清空栈
    while (!s.empty()){
        s.pop();
    }
}
int main()
{
    int n;scanf("%d",&n);
    char s[150];
    char res[150];
    int check[150]={0};
    int numbers[150]={0};
    getchar();
    for(int i=1;i<=n;i++)
    {
        int nnn=0;
        int flag=0;
        printf("Data set #%d:\n",i);
        gets(s);int len=strlen(s);
        int t=0;
		for(int j=0;jleft)continue;这一步是确定当前右括号的左边最近的括号是左括号,如果当前右括号的左边还是右括号,则continue
                    right=j;
                    nnn-=2;
                    res[left]=' ';
                    res[right]=' ';
                    //cout<=0;k--)
            {
                if(res[k]==')'||check[k]==3)
                {
                    right=k;
                    break;
                }
            }
            for(int k=0;k<=right;k++)
            {
                if(check[k]==2)printf("_");
                else if(check[k]==3)
                {
                    printf("|");
                    res[k]=' ';
                }
                else if(res[k]=='('||res[k]==')')printf("|");
                else printf(" ");
            }
            printf("\n");
        }
        cout<

这道题主要的难点是在模拟,判断括号只是栈的一个简单应用,模拟的时候主要思路是模拟出匹配最近的匹配的括号并相连,连上以后把括号变成空格,从而让更远处的括号变成最近的匹配的括号。

你可能感兴趣的:(个人题解,字符串,栈)