0

The expression:

"( a[i]+{-1}*(8-9) )"

should return true since it is valid to write syntax like this. Every left bracket has a right closer in the correct place and all brackets are at legal positions.
I tried to do this via one stack and I know where I'm wrong but I want to know a relevant way to solve this. thx!
My poor poor wrong code:

            string expression = "( a[i]+{-1}*(8-9) ) ";
        Stack<char> expStack = new Stack<char>();
        List<char> rightBracketsHolder = new List<char>();
        for (int i = 0; i < expression.Length; i++)
        {
            if (expression[i] == '{')
            {
                expStack.Push('}');
                Console.Write("}" + " ");
            }
            else if (expression[i] == '(')
            {
                expStack.Push(')');
                Console.Write(")" + " ");
            }
            else if (expression[i] == '[')
            {
                expStack.Push(']');
                Console.Write("]" + " ");
            }
        }
        Console.WriteLine();
        for (int i = 0; i < expression.Length; i++)
        {
            if (expression[i] == '}')
            {
                rightBracketsHolder.Add('}');
                Console.Write(expression[i] + " ");
            }
            else if (expression[i] == ')')
            {
                rightBracketsHolder.Add(')');
                Console.Write(expression[i] + " ");
            }
            else if (expression[i] == ']')
            {
                rightBracketsHolder.Add(']');
                Console.Write(expression[i] + " ");
            }
        }
        Console.WriteLine();
        bool stackResult = checkValidity(expStack, rightBracketsHolder);
        if (stackResult)
            Console.WriteLine("Expression is Valid.");
        else
            Console.WriteLine("\nExpression is not valid.");
        Console.ReadKey();
    }

    private static bool checkValidity(Stack<char> expStack, List<char> leftBracketsHolder)
    {
        Console.WriteLine();
        int length = leftBracketsHolder.Count;
        for (int i = 0; i < length; i++)
        {
            if (expStack.Peek().ToString().Contains(leftBracketsHolder.ToString()))
            {
                leftBracketsHolder.Remove(expStack.Peek());
                expStack.Pop();

            }
        }
        if (expStack.Count == 0 && leftBracketsHolder.Count ==0)
        {
            return true;
        }
        return false;
    }
}
kchinger
  • 339
  • 2
  • 10
N3wbie
  • 227
  • 2
  • 13
  • I think you should use arithmetic expression parser. Have a look at this [question](http://stackoverflow.com/questions/3972854/parse-math-expression) – Bassem Apr 21 '16 at 03:52

2 Answers2

2

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 ' ';
        }
    }
Ankit Bhardwaj
  • 754
  • 8
  • 27
2

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;
   }
}
John Somsky
  • 125
  • 11