Skip to content

Instantly share code, notes, and snippets.

@ofer987
Created July 12, 2017 19:40
Show Gist options
  • Save ofer987/2dd605ed22ae7b5f822cc0c46fadc1ae to your computer and use it in GitHub Desktop.
Save ofer987/2dd605ed22ae7b5f822cc0c46fadc1ae to your computer and use it in GitHub Desktop.
brackets.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
public class Solution
{
public static void Main(String[] args)
{
var t = Convert.ToInt32(Console.ReadLine());
for (int a0 = 0; a0 < t; a0++)
{
Console.WriteLine(IsBalanced(Console.ReadLine()) ? "YES" : "NO");
}
}
private static bool IsBalanced(string str)
{
var openBrackets = new Stack<char>();
foreach (var ch in str.ToCharArray())
{
if (ch == '(' || ch == '[' || ch == '{')
{
openBrackets.Push(ch);
}
else if (ch == ')')
{
if (openBrackets.Count == 0)
{
return false;
}
else if (openBrackets.Peek() == '(')
{
openBrackets.Pop();
}
else
{
return false;
}
}
else if (ch == ']')
{
if (openBrackets.Count == 0)
{
return false;
}
else if (openBrackets.Peek() == '[')
{
openBrackets.Pop();
}
else
{
return false;
}
}
else if (ch == '}')
{
if (openBrackets.Count == 0)
{
return false;
}
else if (openBrackets.Peek() == '{')
{
openBrackets.Pop();
}
else
{
return false;
}
}
else
{
}
}
return openBrackets.Count == 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment