Skip to content

Instantly share code, notes, and snippets.

@wcharczuk
Last active September 23, 2015 21:04
Show Gist options
  • Save wcharczuk/81ef3a977bda3ff5eb0f to your computer and use it in GitHub Desktop.
Save wcharczuk/81ef3a977bda3ff5eb0f to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BalancedParens
{
class Program
{
private static Dictionary<char, char> openingToClose = new Dictionary<char, char>() {
{ '{', '}' },
{ '[', ']' },
{ '(', ')' }
};
static bool Balanced(string body)
{
var expectedCloses = new Stack<char>();
foreach(var c in body)
{
if (openingToClose.ContainsKey(c))
{
expectedCloses.Push(openingToClose[c]);
}
else
{
var expectedClose = expectedCloses.Pop();
if (!c.Equals(expectedClose))
{
return false;
}
}
}
return expectedCloses.Count == 0;
}
static void Main(string[] args)
{
var testCases = new Dictionary<string, bool> {
{ "{}[]()", true},
{ "{}[()]", true},
{ "[{}()]", true },
{ "[(])", false },
{ "([{])}", false },
{ "([{", false }
};
foreach (var testCase in testCases)
{
var result = Balanced(testCase.Key);
if (result != testCase.Value)
{
Console.WriteLine(testCase.Key + " Should Be: " + testCase.Value.ToString());
}
else
{
Console.WriteLine(testCase.Key + "Correct");
}
}
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment