利用栈Stack写一个匹配括号的程序

思路:先写一个匹配函数,再创建一个栈。如果读入的字符与栈顶字符能够匹配则弹栈,否则将读入字符压栈。最后检测栈中是否还有元素:若无,则匹配成功;否则匹配失败。
我曾经的思想误区:第一个元素压栈!!!错误!!!
正确思路:每读入一个元素必须先检测栈内是否为空!!!

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

namespace Pro2
{
    class Program
    {
    	//匹配括号的函数(由于老师题目要求将空格也进行了匹配)
        static bool Match(char input, char element)
        {
            if ((input == ')' && element == '(') || (input == ']' && element == '[') || (input == '}' && element == '{') || (input == ' ' && element == ' '))
                return true;
            else
                return false;
        }

        static void Main(string[] args)
        {
            string str;
            int size = 1000;
            Stack<char> stack = new Stack<char>(size);
            
            Console.Write("Please input a single line(1<=len<=1000): ");
            str = Console.ReadLine();
            for(int i = 0; i < str.Length; i++)
            {
            	//第一个元素必须压栈,否则由于栈为空读取栈顶元素会出错(这种思路是错误的!!!我之前就进了这样的思想误区!
            	//应该是先检测栈中是否有元素,若为空则压栈:否则再进行检测是否匹配!
                if (stack.Count == 0)
                    stack.Push(str[i]);
                else
                {
                    if (Match(str[i], stack.Peek()))
                        stack.Pop();
                    else
                        stack.Push(str[i]);
                }
            }
            if (stack.Count == 0)
                Console.WriteLine("Output: YES");
            else
                Console.WriteLine("Output: NO");
            Console.WriteLine("\r\nPlease press any key to continue...");
            Console.Read();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值