统计左右括号是否成对出现

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;
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值