Advertisement
Qrist

Stack Check the brackets

Jul 26th, 2020
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.01 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace ConsoleApp6
  5. {
  6.     class Program
  7.     {
  8.         static void Main(string[] args)
  9.         {
  10.             string str = "1+(3+2-(2+3)*4)-((3+1)*(4-2)))";
  11.             Stack<int> stack = new Stack<int>();
  12.  
  13.             bool correctBrackets = true;
  14.  
  15.             for (int i = 0; i < str.Length; i++)
  16.             {
  17.                 char ch = str[i];
  18.                 if (ch == '(')
  19.                 {
  20.                     stack.Push(i);
  21.                 }
  22.                 else if (ch == ')')
  23.                 {
  24.                     if (stack.Count == 0)
  25.                     {
  26.                         correctBrackets = false;
  27.                         break;
  28.                     }
  29.                     stack.Pop();
  30.  
  31.                 }
  32.             }
  33.             if (stack.Count != 0)
  34.             {
  35.                 correctBrackets = false;
  36.             }
  37.             Console.WriteLine("Are the brackets correct? " + correctBrackets );
  38.  
  39.         }        
  40.     }
  41. }
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement