using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CheckParenthesisMatch
{
class Program
{
static void Main(string[] args)
{
string test = "(I(L)((ov)eYo()uHe)iHei#";
Char[] testChar = test.ToCharArray();
bool result = CheckIfParenthesisMatch(testChar);
bool result2 = CheckIfParenthesisMatch2(testChar);
Console.WriteLine("The parenthesis of the string is match? {0}", result);
Console.WriteLine("The parenthesis of the string is match2? {0}", result2);
Console.ReadKey();
}
private static bool CheckIfParenthesisMatch(char[] arr)
{
char[] temp = new char[arr.Length + 1];
int top = 0; //top用作栈顶指针
temp[top] = '#'; //‘#’先入栈,用于和表达式结束符号‘#’匹配。
int i = 0;
while (arr[i] != '#') //逐字符处理字符表达式的数组。
switch (arr[i])
{
case '(': temp[++top] = '('; i++; break;
case ')': if (temp[top] == '(') { top--; i++; break; } else { return false; }
default: i++; break;
}
if (temp[top] == '#') return true;
else return false;
}
/// <summary>
/// 不借助特殊符号作为退出检查标记
/// </summary>
/// <param name="arr"></param>
/// <returns></returns>
private static bool CheckIfParenthesisMatch2(char[] arr)
{
char[] temp = new char[arr.Length + 1];
int top = -1; //这样temp[++top]就是第一个位置
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == '(') temp[++top] = '('; //此处使用++top很重要,先加一
else if (arr[i] == ')')
{
if (temp[top] == '(') top--;
else break;
}
}
//Console.WriteLine("Top is: {0}", top);
return top == -1 ? true : false;
}
}
}
统计左右括号是否成对出现
最新推荐文章于 2020-04-22 23:09:20 发布