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