Skip to content

Instantly share code, notes, and snippets.

@jasonbrice
Created April 29, 2015 16:07
Show Gist options
  • Save jasonbrice/e6546d1476b7f4935cc5 to your computer and use it in GitHub Desktop.
Save jasonbrice/e6546d1476b7f4935cc5 to your computer and use it in GitHub Desktop.
Check whether a set of curly braces, brackets and parentheses are well-formed
private static bool CheckWellFormed(string input)
{
var stack = new Stack<char>();
// dictionary of matching starting and ending pairs
var allowedChars = new Dictionary<char, char>() { { '(', ')' }, { '[', ']' }, { '{', '}' } };
var wellFormated = true;
foreach (var chr in input)
{
if (allowedChars.ContainsKey(chr))
{
// if starting char then push on stack
stack.Push(chr);
}
// ContainsValue is linear but with a small number is faster than creating another object
else if (allowedChars.ContainsValue(chr))
{
// make sure something to pop if not then know it's not well formated
wellFormated = stack.Any();
if (wellFormated)
{
// hit ending char grab previous starting char
var startingChar = stack.Pop();
// check it is in the dictionary
wellFormated = allowedChars.Contains(new KeyValuePair<char, char>(startingChar, chr));
}
// if not wellformated exit loop no need to continue
if (!wellFormated)
{
break;
}
}
}
return wellFormated;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment