class MatchTest
{
static void Main(string[] args)
{
MatchTest test = new MatchTest();
test.BuildTest();
}
public void BuildTest()
{
//检验正确的
Console.WriteLine();
Console.WriteLine("检验正确的");
Console.WriteLine(this.ValidateMatch(this.BuilderSymbolsSet(this.TestSentenceRight())));
//检验错误的,少了一个(奇数)匹配符号
Console.WriteLine();
Console.WriteLine("检验错误的,少了一个(奇数)匹配符号");
Console.WriteLine(this.ValidateMatch(this.BuilderSymbolsSet(this.TestSentenceWrong())));
//检验错误的,少了两个(偶数)匹配符号
Console.WriteLine();
Console.WriteLine("检验错误的,少了两个(偶数)匹配符号");
Console.WriteLine(this.ValidateMatch(this.BuilderSymbolsSet(this.TestSentenceWrongOther())));
Console.ReadLine();
}
private string TestSentenceRight()
{
return "{ if( true ){ return;} }";
}
private string TestSentenceWrong()
{
return "{ if( true ) { return;} ";
}
private string TestSentenceWrongOther()
{
return "{ if( true { return;} ";
}
public List<char> BuilderSymbolsSet(string sentence)
{
List<char> symbols = new List<char>();
foreach (char item in sentence)
{
if (item == '{' ||
item == '}' ||
item == '(' ||
item == ')')
{
symbols.Add(item);
}
}
return symbols;
}
public bool ValidateMatch(List<char> symbols)
{
Stack<char> tempStack = new Stack<char>();
if (symbols.Count == 0)
{
throw new FormatException("该语句没有内容");
}
if (symbols.Count % 2 != 0)
{
Console.WriteLine("在检验符号匹配时,检验到符号集的个数为奇数,所以不匹配");
return false;
}
foreach (char item in symbols)
{
if (tempStack.Count == 0)
{
//如果所加入的第一个符号不是左符号,那么在留在栈里。
tempStack.Push(item);
}
else
{
char symbol = tempStack.Peek();
if ( (item == '}' && symbol == '{') ||
(item == ')' && symbol == '(') )
{
tempStack.Pop();
}
else
{
tempStack.Push(item);
}
}
}
if (tempStack.Count == 0)
{
return true;
}
else
{
return false;
}
}
}