UVA 673 Parentheses Balance(栈的操作)

本文深入探讨了经典的括号匹配问题,通过一个具体的程序实例,详细讲解了如何使用栈来检查由圆括号和方括号组成的字符串是否正确配对。代码采用C语言实现,通过逐个扫描字符串中的字符,并利用栈进行出栈和入栈操作,判断括号的正确性。

You are given a string consisting of parentheses () and []. A string of this type is said to be correct:

    (a) if it is the empty string

    (b) if A and B are correct, AB is correct,

  (c) if A is correct, (A) and [A] is correct.

Write a program that takes a sequence of strings of this type and check their correctness. Your program can assume that the maximum string length is 128.

Input

The file contains a positive integer n and a sequence of n strings of parentheses ‘()’ and ‘[]’, one string a line.

Output

A sequence of ‘Yes’ or ‘No’ on the output file.

Sample Input

3

([])

(([()])))

([()[]()])()

Sample Output

Yes

No

Yes

分析: 此题是经典的括号匹配问题,运用到栈的知识点,出站,入栈操作。

代码如下:

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

int main()
{
    char stack[150],s[150];
    int top,low,i,n,l,find;
    scanf("%d",&n);
    getchar();
    while(n--)
    {
        find = 1;
        gets(s);
        memset(stack,0,sizeof(stack));
        top=low=-1;
        l=strlen(s);
        for(i=0;i<l;i++)
        {
            if(s[i]=='('||s[i]=='[')
            {//如果是左括号则入栈,等待匹配 
                stack[++top]=s[i];
            }
            else if(s[i]==')')
            {//如果为右小括号 
                if(stack[top]=='(')//可以匹配 
                    top--;
                else
                {//不能匹配 
                    find=0;
                    break;
                }
            }
            else if(s[i]==']')
            {//如果为右中括号 
                if(stack[top]=='[')//可以匹配
                    top--;
                else
                {//不能匹配
                    find=0;
                    break;
                }
            }
            else
            {//存在其他字符时 
                find=0;
                break;
            }
        }
        if(i==l&&top!=low)
            find=0;//存在多余的括号 
        if(find==0)
        {
            printf("No\n");
        }
        else
        {
            printf("Yes\n");
        }
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值