括号配对问题

描述
现在,有一行括号序列,请你检查这行括号是否配对。
输入
第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有"[","]","(",")"四种字符
输出
每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes,如果不配对则输出No
样例输入
3
[(])
(])
([[]()])
样例输出
No
No
Yes



这一题,我提交了7次才通过。我使用了goto,这个是书本上强烈建议不让用的,但是我发现goto有时
就像汇编的Jmp一样,想到哪到哪,但是如果和while连用,就有可能出现一些错误。
while和goto尽量不要连用,还有就是注意输出格式,如让输出Yes,你不能输出YES.
一般牵涉到表达式的就要用到递归、堆栈等,能用堆栈的一般就能递归,但是我的递归式总是不正确。
注意头文件:用scanf就要加<stdio.h>;用string就加<string>
下面是正确的代码:
View Code
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<stack>

#include<stdio.h>


using namespace std;


int main()
{
    int n;
    int i;
    string str;
    scanf("%d",&n);    

lable:
    if(n==0)
        return 0;  
    cin>>str;        
        stack<char> sta;
        for(i=0;i<str.length();i++)
        {
            switch(str[i])
            {
            case '(':
                sta.push(str[i]);
                break;
            case '[':
                sta.push(str[i]);
                break;
            case ')':
                if(sta.empty()||sta.top()=='[')//堆栈空
                {
                    printf("No\n");
                    n--;//goto之前一定要改变临界条件
                    goto lable;//break; //对case
                }
                if(sta.top()=='(')
                {
                    sta.pop();
                }            
                break;
            case ']':
                if(sta.empty()||sta.top()=='(')//堆栈空
                {
                    printf("No\n");
                    n--;//goto之前一定要改变临界条件
                    goto lable;
                }
                if(sta.top()=='[')
                sta.pop();
                break;
            }            
        }
        if(sta.empty())
                printf("Yes\n");
        else
            printf("No\n");
        n--;
        goto lable;
            
    

}

 

posted @ 2012-04-14 21:10  金河  阅读(358)  评论(0编辑  收藏  举报