BracketsBalanced

mail@pastecode.io avatar
unknown
csharp
a year ago
1.5 kB
0
Indexable
Never
using System;
using System.Collections.Generic;

public class BracketBalancer
{
    public static bool AreBracketsBalanced(string input)
    {
        Stack<char> stack = new Stack<char>();

        foreach (char c in input)
        {
            if (IsOpeningBracket(c))
            {
                stack.Push(c);
            }
            else if (IsClosingBracket(c))
            {
                if (stack.Count == 0 || !BracketsMatch(stack.Peek(), c))
                {
                    return false;
                }
                stack.Pop();
            }
        }

        return stack.Count == 0;
    }

    private static bool IsOpeningBracket(char c)
    {
        return c == '(' || c == '[' || c == '{';
    }

    private static bool IsClosingBracket(char c)
    {
        return c == ')' || c == ']' || c == '}';
    }

    private static bool BracketsMatch(char opening, char closing)
    {
        return (opening == '(' && closing == ')') ||
               (opening == '[' && closing == ']') ||
               (opening == '{' && closing == '}');
    }
}

public class Program
{
    public static void Main()
    {
        string input = Console.ReadLine();

        if (BracketBalancer.AreBracketsBalanced(input))
        {
            Console.WriteLine("Скобите са балансирани.");
        }
        else
        {
            Console.WriteLine("Скобите не са балансирани.");
        }
    }
}