括号匹配问题

写一个小程序玩玩:括号匹配问题。要求如下:

本题目要求编一个程序,该程序能够输入一段字符串进行括弧匹配检查。如果语句中"("和")"数目相等,且能够完整的匹配成对,此时输出"正确"。否则输出"错误"。

方法一:计数式

基本思路:思路:设置一个计数器counter,遇到(,就+1,遇到),就-1,最后看counter是不是0就行.对于")("这种情况,可以用首个)>0来排除。

实现代码:

/// <summary>
/// 返回0为匹配,否则不匹配
/// </summary>
public static int Brackets(string input)
{ 
    //思路:设置一个计数器counter
    //遇到(,就+1
    //遇到),就-1
    //最后看counter是不是0就行
    //对于")("这种情况,可以用首个)>0来排除

    int counter = 0;
    string result = string.Empty;

    for (int i = 0; i < input.Length; i++)
    {
        if (input[i]!='\0') //not end
        {
            if (input[i]=='(')
            {
                counter++;
            }
            if (input[i]==')')
            {
                counter--;
                if (counter<0)
                {
                    break;//跳出循环
                }
            }
        }
    }

    //跳出循环执行这里
    return counter;
}

测试代码:

static void Main(string[] args)
{
    string str = string.Empty;
    Console.WriteLine("请输入:");
    str = Console.ReadLine();

    int result = BracketsMatch.Brackets(str);
    Console.WriteLine(result == 0 ? "yes" : "no");
}

结果:

 

方法二:堆栈、链表实现

/*
 *
 * 算法的设计思想:
    1. 凡出现左括弧,则进栈
    2. 凡出现右括弧,首先检查栈是否空
        若栈空,则表明右括号多了
        否则和栈顶元素比较
                   若相匹配,则左括弧出栈
                                     否则匹配不正确
    3. 表达式检验结束时,
         若栈空,则匹配正确
                        否则表明左括号多了
 * 
 */
public static bool BracketStack(string input)
{
    Stack<char> stack = new Stack<char>();
    for (int i = 0; i < input.Length; i++)
    {
        char curChar = input[i];
        if (curChar == '(')
        {
            stack.Push(curChar);
        }
        else if (curChar == ')')
        {
            if (stack.Count == 0)
            {//右括号)多了
                return false;
            }
            else
            {
                char topChar = stack.Peek();//Peek():取栈顶元素
                if (topChar == '(')
                {//如果匹配就出栈
                    stack.Pop();
                }
                else
                {//左右括号不匹配
                    return false;
                }
            }
        }
    }

    if (stack.Count == 0)
    {//匹配
        return true;
    }
    else
    {//左括号(多了
        return false;
    }
}

方法三:递归

这时候,题目变了。

括号匹配:给定字符串,输出括号是否匹配,例如,"()" yes;")(" no;"(abcd(e)" no;"(a)(b)" yes。要求必须用递归写,整个实现不可以出现一个循环语句。

递归实现:

 todo...

参考:
http://www.rupeng.com/forum/thread-19178-1-1.html

http://weibo.com/1915548291/zxoyRDriV

http://hi.baidu.com/babyforyou/item/0d83391f5c1db80eb88a1a1f

http://chenzhenianqing.cn/articles/660.html

原文地址:https://www.cnblogs.com/fanyong/p/3114506.html