栈的应用举例:括号匹配(C#)

假设表达式允许包含两种括号:圆括号和方括号,其嵌套的顺序随意,即[ ( [ ] ( ) ) ]等为正确的格式,[ ( ]或( ( [ ) )为错误的格式。
当计算机接收左括号时,括号入栈,当计算机接收右括号时,取得栈顶元素,并检查是否和左括号匹配,]对应[,)对应(,若匹配,则出栈。因此当程序的开始和结束时,栈都应该是空的。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = "[([]())]";
            string ss = "[([)]]";
            Stack<char> newstack = new Stack<char>();
            foreach (char ch in ss)
            {
                switch (ch)
                {
                    case '['://左括号,入栈
                        newstack.Push(ch);
                        break;
                    case '('://左括号,入栈
                        newstack.Push(ch);
                        break;
                    case ')':
                        if (newstack.Peek() == '(')
                        {
                            newstack.Pop();//出栈
                        }
                        break;
                    case ']':
                        if (newstack.Peek() == '[')
                        {
                            newstack.Pop();//出栈
                        }
                        break;
                }
            }
            if (newstack.Count == 0)
            {
                Console.WriteLine(s + "格式正确");
            }
            else
            {
                Console.WriteLine(s+"格式错误");
            }
            Console.ReadLine();
        }
    }
}
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值