Here is the general goal of this exercise:
For each string, print whether or not the string of brackets is balanced on a new line. If the brackets are balanced, print YES; otherwise, print NO.
Please comment as this was a job interview and I had 30 mins to give something working and the best performance wise.
using System; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace JobInterviewTests { [TestClass] public class UnitTest1 { [TestMethod] public void TestMethod1() { List<string> list = new List<string> {"({[]})", "][(]}})("}; foreach (var barcketsList in list) { string expression = barcketsList; Stack<char> stack = new Stack<char>(); char[] symbols = expression.ToCharArray(); if (symbols.Length == 0) { break; } bool flagPrint = false; for (int start = 0; start < symbols.Count(); start++) { char temp = symbols[start]; if (temp == '[' || temp == '{' || temp == '(') { stack.Push(temp); } else { if (stack.Count == 0) //only closer no opening { Console.WriteLine("NO"); flagPrint = true; break; } char top = stack.Peek(); if (temp == ']') { if (top != '[') { break; } stack.Pop(); } else if (temp == '}') { if (top != '{') { break; } stack.Pop(); } else // temp == ')' { if (top != '(') { break; } stack.Pop(); } } } if (!stack.Any() && !flagPrint) { Console.WriteLine("YES"); } else if (!flagPrint) { Console.WriteLine("NO"); } } } } }