Balanced Paranthesis

 avatar
unknown
plain_text
a year ago
1.2 kB
3
Indexable
using System;
using System.Collections.Generic;
using System.Collections;

class Program
{
    static void Main(string[] args)
    {
        char[] chars = Console.ReadLine().ToCharArray();
        // half in stack, half in queue
        Stack<char> firstHalf = new Stack<char>();
        Queue<char> secondHalf = new Queue<char>();
        int length = chars.Length;
        for (int i = 0; i < length / 2; i++) // if length = 8, starts from 0 and ends at 4 (0, 1, 2, 3 incl)
        {
            firstHalf.Push(chars[i]);
        }

        for (int j = length / 2; j < length; j++) // if length = 8, starts from 4 and ends at 7 (4, 5, 6, 7 incl)
        {
            secondHalf.Enqueue(chars[j]);
        }

        bool equal = true;
        while (firstHalf.Count > 0)
        {
            char charFromStack = firstHalf.Pop();
            char charFromQueue = secondHalf.Dequeue();
            
            if (charFromStack != charFromQueue)
            {
                equal = false; break;
            }
        }

        if (equal)
        {
            Console.WriteLine("YES");
        }
        else
        {
            Console.WriteLine("NO");
        }
    }
}
Editor is loading...
Leave a Comment