Advertisement
gabi11

Stacks and Queues - 08. Balanced Parenthesis

May 11th, 2019
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.49 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6.  
  7. namespace Advanced
  8. {
  9.     class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.             string brackets = Console.ReadLine();
  14.  
  15.             var stackOfBrackets = new Stack<char>();
  16.  
  17.             bool isValid = true;
  18.  
  19.             for (int i = 0; i < brackets.Length; i++)
  20.             {
  21.                 char currentBracket = brackets[i];
  22.  
  23.                 if (currentBracket == '(' || currentBracket == '[' || currentBracket == '{')
  24.                 {
  25.                     stackOfBrackets.Push(currentBracket);
  26.                 }
  27.  
  28.                 if (stackOfBrackets.Count == 0)
  29.                 {
  30.                     isValid = false;
  31.                     break;
  32.                 }
  33.  
  34.                 if (stackOfBrackets.Count != 0)
  35.                 {
  36.                     if (stackOfBrackets.Peek() == '(' && currentBracket == ')'
  37.                         || stackOfBrackets.Peek() == '[' && currentBracket == ']'
  38.                         || stackOfBrackets.Peek() == '{' && currentBracket == '}')
  39.                     {
  40.                         stackOfBrackets.Pop();
  41.                     }
  42.  
  43.                 }
  44.             }
  45.  
  46.             if (isValid && stackOfBrackets.Count == 0)
  47.             {
  48.                 Console.WriteLine("YES");
  49.             }
  50.  
  51.             else
  52.             {
  53.                 Console.WriteLine("NO");
  54.             }
  55.         }
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement