题目链接 : http://acm.nyist.net/JudgeOnline/problem.php?pid=2
方法图解:
C#代码
using System;
using System.Collections.Generic;
#region 描述
//描述
//现在,有一行括号序列,请你检查这行括号是否配对。
//输入
//第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有"[","]","(",")"四种字符
//输出
//每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes, 如果不配对则输出No
#endregion
namespace ACM_PairBracket
{
class Program
{
static void Main(string[] args)
{
int count = Convert.ToInt32(Console.ReadLine());
List<List<char>> testList = new List<List<char>>();
List<char> test;
for (int c = 0; c < count; c++)
{
test = new List<char>();
string input = Convert.ToString(Console.ReadLine());
for (int i = 0; i < input.Length; i++) test.Add(input[i]);
testList.Add(test);
}
for (int i = 0; i < count; i++) Console.WriteLine(Judge(testList[i]));
Console.ReadKey();
}
static string Judge(List<char> test)
{
Dictionary<char, char> dict = new Dictionary<char, char> { { '(', '1' }, { '[', '1' }, { ')', '(' }, { ']', '[' }};
List<char> list = new List<char>();
list = test;
if (list.Count % 2 == 1) return "No";
// 去内侧括号
while (true)
{
bool flag = false;
for(int i = 0;i < list.Count - 1;i++)
{
if(list[i] == dict[list[i+1]])
{
list.RemoveAt(i + 1);
list.RemoveAt(i);
flag = true;
}
}
if (list.Count == 0) return "Yes";
if (flag == false) return "No";
}
}
}
}