Last active
September 23, 2015 21:04
-
-
Save wcharczuk/81ef3a977bda3ff5eb0f to your computer and use it in GitHub Desktop.
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.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