您的位置:首页 > 编程语言 > C#

C#编写程序判断给定的表达式字符串中的括号是否正确匹配(成对出现)

2019-04-10 21:17 323 查看

C#编写程序判断给定的表达式字符串中的括号是否正确匹配(成对出现)
例如:
正确的字符串:{[{}{}]}[()],或{{}{}},或者[]{}()
错误的字符串:{()}[),或{(}),或({[{

using System;
using System.Collections.Generic;

namespace _111
{
class Program
{
public static void Main(string[] args)
{
string exp = “{()}[{}][()]”;
if (isCorrect(exp))
{
Console.WriteLine(“正确”);
}
else
{
Console.WriteLine(“错误”);
}

Console.ReadKey();
}

public static bool isCorrect(string exp)
{
int a = 0;
List<int> l = new List<int>();
if (exp != null)
{
for (int i = 0; i < exp.Length; i++)
{
switch (exp[i])
{
case '{':
a = 3;
break;
case '[':
a = 2;
break;
case '(':
a = 1;
break;
case '}':
a = -3;
break;
case ']':
a = -2;
break;
case ')':
a = -1;
break;
default:
break;
}
if (a > 0)
{
l.Add(a);

}
if (a < 0)
{
if (l[l.Count - 1] + a != 0)
{
return false;
}
else
{
l.Remove(l[l.Count - 1]);
}
}

}
}
if (l.Count == 0)
return true;
else
return false;
}
}

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐