例如:
正确的字符串:{[{}{}]}{()},或{{}{}},或者[]{}{}
错误的字符串:{()}[),或{(}),或者({[{
给定字符串:String exp="{()}[{}]";判断是否正确匹配(成对出现)
static void Main(string[] args)
{
String exp = "{()}[{}]";
if (IsCorrect(exp))
{
Console.WriteLine("The expression is correct");
}
else
{
Console.WriteLine("The expression is not correct");
}
}
实现方法:
public static bool IsCorrect(string exp)
{
int num = 0;//标记
List<int> numList = new List<int>();
if (string.IsNullOrEmpty(exp))
{
for (int i = 0; i < exp.Length; i++)
{
switch (exp[i])
{
case '{':
num = 3;
break;
case '[':
num = 2;
break;
case '(':
num = 1;
break;
case '}':
num = -3;
break;
case ']':
num = -2;
break;
case ')':
num = -1;
break;
}
if (num > 0)
numList.Add(num);
if (num < 0)
{
if (numList[numList.Count - 1] + num == 0)
numList.Remove(numList[numList.Count - 1]);
else
return false;
}
}
}
if (numList.Count == 0)
return true;
else
return false;
}
}
运行结果: