📌  相关文章
📜  使用堆栈检查表达式(格式良好)中的平衡括号的 C# 程序

📅  最后修改于: 2022-05-13 01:57:08.304000             🧑  作者: Mango

使用堆栈检查表达式(格式良好)中的平衡括号的 C# 程序

给定一个表达式字符串exp,编写一个程序来检查 exp 中“{“, “}”, “(“, “)”, “[”, “]” 的对和顺序是否正确。

示例

检查表达式中的平衡括号

算法:

  • 声明一个字符栈 S。
  • 现在遍历表达式字符串exp。
    1. 如果当前字符是起始括号( '(' 或 '{' 或 '[' ),则将其推入堆栈。
    2. 如果当前字符是右括号( ')' 或 '}' 或 ']' ),则从堆栈中弹出,如果弹出的字符是匹配的起始括号,则可以,否则括号不平衡。
  • 完全遍历后,如果堆栈中还有一些起始括号,则“不平衡”

下图是上述方法的试运行:

下面是上述方法的实现:

C#
// C# program for checking
// balanced Brackets
using System;
using System.Collections.Generic;
  
public class BalancedBrackets {
    public class stack {
        public int top = -1;
        public char[] items = new char[100];
  
        public void push(char x)
        {
            if (top == 99) 
            {
                Console.WriteLine("Stack full");
            }
            else {
                items[++top] = x;
            }
        }
  
        char pop()
        {
            if (top == -1) 
            {
                Console.WriteLine("Underflow error");
                return '�';
            }
            else 
            {
                char element = items[top];
                top--;
                return element;
            }
        }
  
        Boolean isEmpty()
        {
            return (top == -1) ? true : false;
        }
    }
  
    // Returns true if character1 and character2
    // are matching left and right brackets */
    static Boolean isMatchingPair(char character1,
                                  char character2)
    {
        if (character1 == '(' && character2 == ')')
            return true;
        else if (character1 == '{' && character2 == '}')
            return true;
        else if (character1 == '[' && character2 == ']')
            return true;
        else
            return false;
    }
  
    // Return true if expression has balanced
    // Brackets
    static Boolean areBracketsBalanced(char[] exp)
    {
        // Declare an empty character stack */
        Stack st = new Stack();
  
        // Traverse the given expression to
        //   check matching brackets
        for (int i = 0; i < exp.Length; i++) 
        {
            // If the exp[i] is a starting
            // bracket then push it
            if (exp[i] == '{' || exp[i] == '('
                || exp[i] == '[')
                st.Push(exp[i]);
  
            //  If exp[i] is an ending bracket
            //  then pop from stack and check if the
            //   popped bracket is a matching pair
            if (exp[i] == '}' || exp[i] == ')'
                || exp[i] == ']') {
  
                // If we see an ending bracket without
                //   a pair then return false
                if (st.Count == 0) 
                {
                    return false;
                }
  
                // Pop the top element from stack, if
                // it is not a pair brackets of
                // character then there is a mismatch. This
                // happens for expressions like {(})
                else if (!isMatchingPair(st.Pop(),
                                         exp[i])) {
                    return false;
                }
            }
        }
  
        // If there is something left in expression
        // then there is a starting bracket without
        // a closing bracket
  
        if (st.Count == 0)
            return true; // balanced
        else 
        { 
            // not balanced
            return false;
        }
    }
  
    // Driver code
    public static void Main(String[] args)
    {
        char[] exp = { '{', '(', ')', '}', '[', ']' };
  
        // Function call
        if (areBracketsBalanced(exp))
            Console.WriteLine("Balanced ");
        else
            Console.WriteLine("Not Balanced ");
    }
}
  
// This code is contributed by 29AjayKumar


输出
Balanced

时间复杂度: O(n)
辅助空间:堆栈的 O(n)。

有关更多详细信息,请参阅有关使用 Stack 的表达式(格式良好)检查平衡括号的完整文章!