C语言 —— 括号配对问题(不使用栈)

最近在南阳理工的OJ上刷题,看到一个有点意思的题目
网上的答案大多都使用了栈,可惜我还没有学习数据结构,所以只能用简单的方法来解决

题目的链接在这 http://acm.nyist.net/JudgeOnline/problem.php?pid=2

描叙:

现在,有一行括号序列,请你检查这行括号是否配对。

 

输入:

第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一

个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有"[","]","(",")"四

种字符。

 

输出:

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

 

代码如下:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main()
{
    int n;
    char str[10000];
    void deal( char str[]);
    
    scanf("%d",&n);
    while(n--)
    {
        scanf("%s",str);
        deal( str);
    }
}

void deal( char str[])
{
    int len = strlen( str);
    int i,j,n,flag;
    
    if( len%2 != 0 || str[0] == ')' || str[0] == ']' )
    {
        printf("No\n");
    }
    else
    {
        for( i = 0; i < len; i++)
        {
            if( str[i] == ')' || str[i] == ']')
            {
                for( j = i-1; j > -1; j--)
                {
                    if( str[j] == '0' )
                        continue;
                    if( (int)(str[i] - str[j]) != 1 && (int)(str[i] - str[j]) != 2)
                    {
                        printf("No\n");
                        return;
                    }
                    else
                    {
                        str[i] = str[j] = '0';
                        break;
                    }
                }
            }
        }
        if( str[ len-1] == '0' )
            printf("Yes\n");
    }
}
posted @ 2014-05-28 19:53  lleo小浩  阅读(2877)  评论(0)    收藏  举报