Created
July 12, 2017 19:40
-
-
Save ofer987/2dd605ed22ae7b5f822cc0c46fadc1ae to your computer and use it in GitHub Desktop.
brackets.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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