nyoj 2括号匹配 栈入门

来源:互联网 发布:造梦西游4修改器mac版 编辑:程序博客网 时间:2024/06/04 17:42


//思想是模拟栈,第一个是最优算法,巧妙的运用了指针

#include <stdio.h>
#include <string.h>
int main()
{
    int n,i,top;
    scanf("%d",&n);
    getchar();
    while(n--)
    {
        char s[10001],ch;
        top=-1;
        while((ch=getchar())!='\n')
        {
            if(ch==')'&&top>=0&&s[top]=='(')     //top>=0    如果为左括号,并且栈s不为空,并且上一个括号与之对应
                top--;                                             //出栈
            else
                if(ch==']'&&top>=0&&s[top]=='[')   
                    top--;
            else
                s[++top]=ch;                               //否则入栈
        }
        if(top==-1)
            printf("Yes\n");
        else
            printf("No\n");
    }
    return 0;
}




//第二种方法是,c语言构造栈实现

//定义一个结构体模拟栈,写好初始化,入栈,出栈函数
#include<stdio.h>
struct stack
{
    char str[10005];
    int top;
};
void Initstack(stack& a)//**构造一个空栈**//
{
    a.top=-1;
}
void push(stack& a,char item)//**往栈里面插入一个新元素**//
{
    a.top++;
    a.str[a.top]=item;
}
void pop(stack& a)//**删除栈顶元素并返回其值**//
{
    a.top--;
}
int main()
{
    int s;
    char ch;
    scanf("%d",&s);
    getchar();
    while(s--)
    {
        stack a;
        Initstack(a);
       while(scanf("%c",&ch)&&ch!='\n')                      //核心操作
        {
            if(ch=='['||ch=='(')                                          
                push(a,ch);
            else
           {
                if(a.str[a.top]=='['&&ch==']')
                {
                   pop(a);
                }
                else if(a.str[a.top]=='('&&ch==')')
                {
                    pop(a);
                }
                else
                {
                    push(a,ch);
                }
            }
        }
        if(a.top==-1)//**如果栈为空说明括号配对完成**//
        {
            printf("Yes\n");
        }
        else
        {
            printf("No\n");
       }
    }
    return 0;
}














0 0
原创粉丝点击