C# checking if expression is brackets valid [closed]

假如想象 提交于 2019-12-02 08:44:37

This code will solve your purpose -

static void Main(string[] args)
    {
        bool error = false;
        var str = "( a[i]+{-1}*(8-9) )";
        Stack<char> stack = new Stack<char>();
        foreach (var item in str.ToCharArray())
        {
            if (item == '(' || item == '{' || item == '[')
            {
                stack.Push(item);
            }
            else if(item == ')' || item == '}' || item == ']')
            {
                if (stack.Peek() != GetComplementBracket(item))
                {
                    error = true;
                    break;
                }
            }
        }

        if (error)
            Console.WriteLine("Incorrect brackets");
        else
            Console.WriteLine("Brackets are fine");
        Console.ReadLine();
    }

    private static char GetComplementBracket(char item)
    {
        switch (item)
        {
            case ')':
                return '(';
            case '}':
                return '{';
            case ']':
                return '[';
            default:
                return ' ';
        }
    }

You need to pop things off the stack as the closing occurs. Try the following code. It will push an open brace/bracket/parenthesis on the stack and the first thing then it will be popped from the stack by a corresponding close. Otherwise it is invalid. If you have no opens on the stack when a close is encountered, it is invalid. If you have any extra opens when you are complete it is invalid.

I also used a switch statement instead of an if statement just because I thought it was easier to read.

using System;
using System.Collections.Generic;

public class Program
{
   public static void Main()
   {
      string expression = "( a[i]+{-1}*(8-9) ) ";
      bool stackResult = checkValidity(expression);

      if (stackResult)
         Console.WriteLine("Expression is Valid.");
      else
         Console.WriteLine("\nExpression is not valid.");
   }

   private static bool checkValidity(string expression)
   {
      Stack<char> openStack = new Stack<char>();
      foreach (char c in expression)
      {
         switch (c)
         {
            case '{':
            case '(':
            case '[':
               openStack.Push(c);
               break;
            case '}':
               if (openStack.Count == 0 || openStack.Peek() != '{')
               {
                  return false;
               }
               openStack.Pop();       
               break;
            case ')':
               if (openStack.Count == 0 || openStack.Peek() != '(')
               {
                  return false;
               }
               openStack.Pop();       
               break;
            case ']':
               if (openStack.Count == 0 || openStack.Peek() != '[')
               {
                  return false;
               }
               openStack.Pop();       
               break;
            default:
               break;
         }
      }
      return openStack.Count == 0;
   }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!