Advertisement
Guest User

08. BalancedParentheses

a guest
Jul 24th, 2019
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.74 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5.  
  6. namespace E08_BalancedParentheses
  7. {
  8.     class BalancedParentheses
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             // 75% - 2 Wrong Tests - 4, 8
  13.             // https://judge.softuni.bg/Contests/Practice/Index/1447#7
  14.  
  15.             string input = Console.ReadLine();
  16.             if (input.Length % 2 != 0 || input == "")
  17.             {
  18.                 Console.WriteLine("NO");
  19.             }
  20.             else
  21.             {
  22.                 int halfStringLength = input.Length / 2;
  23.                 string firstHalf = input.Substring(0, halfStringLength);
  24.                 string secondHalf = input.Substring(halfStringLength);
  25.                 Stack<char> first = new Stack<char>(firstHalf);
  26.                 Stack<char> second = new Stack<char>(secondHalf.Reverse());
  27.                 bool isValid = true;
  28.                 for (int i = 0; i < halfStringLength; i++)
  29.                 {
  30.                     if ((first.Peek() == '(' && second.Peek() == ')')
  31.                         || (first.Peek() == '[' && second.Peek() == ']')
  32.                         || (first.Peek() == '{' && second.Peek() == '}'))
  33.                     {
  34.                         first.Pop();
  35.                         second.Pop();
  36.                     }
  37.                     else
  38.                     {
  39.                         isValid = false;
  40.                         break;
  41.                     }
  42.                 }
  43.  
  44.                 if (isValid)
  45.                 {
  46.                     Console.WriteLine("YES");
  47.                 }
  48.                 else
  49.                 {
  50.                     Console.WriteLine("NO");
  51.                 }
  52.             }
  53.         }
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement