通过栈Stack实现括号匹配的语法检查
算法的设计思想:
出现左括弧则进栈;
出现右括弧则首先检测栈是否为空,
若栈空则表明此右括弧多余,表达式不匹配。
否则和栈顶数据比较,若匹配则栈顶出栈。
否则表明表达式不匹配;
最后若栈空且没有做鱼右括弧则匹配正确,否则表明不匹配。
class Program
{
static void Main(string[] args)
{
string s = "{(())4}";
Console.WriteLine(Match(s));
Console.ReadKey();
}
static bool Match(string s)
{
if (string.IsNullOrEmpty(s))
{
throw new Exception("空的字符串");
}
Stack<string> stack = new Stack<string>();
foreach (char temp in s)
{
switch (temp)
{
case '[':
stack.Push("]");
break;
case '(':
stack.Push(")");
break;
case '{':
stack.Push("}");
break;
case '}':
case ')':
case ']':
if (temp.Equals(char.Parse(stack.Peek())))
{
stack.Pop();
return true;
}
else
{
return false;
}
}
}
if (stack.Count==0)
{
return true;
}
return false;
}
}