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