I was given an assignment to check for balanced parentheses from an arbitrary string where parentheses are defined as (, [ or {
and their respective "closing" parentheses. The other requirement for the assignment was that I had to use either Stack<T>
, Queue<T>
or List<T>
.
Here is my implementation:
private static void CheckParentheses()
{
Console.Write("Please enter the string you wist to check formity of: ");
var input = Console.ReadLine();
var stack = new Stack<char>();
char[] allowedChars = { '(', '[', '{', ')', ']', '}' };
foreach (char chr in input)
if (allowedChars.Any(x => x == chr))
stack.Push(chr);
var reverseStack = stack.Reverse();
var sequencedBalanced = reverseStack.SequenceEqual(stack, BalancedParanthesisComparer.Instance);
Console.WriteLine("The input string was {0}well formed", sequencedBalanced ? string.Empty : "NOT ");
}
public sealed class BalancedParanthesisComparer : EqualityComparer<char>
{
private static readonly BalancedParanthesisComparer _instance = new BalancedParanthesisComparer();
private BalancedParanthesisComparer() { }
public static BalancedParanthesisComparer Instance { get { return _instance; } }
public override bool Equals(char x, char y)
{
if ((x == '(' && y == ')') || (y == '(' && x == ')'))
return true;
if ((x == '[' && y == ']') || (y == '[' && x == ']'))
return true;
if (x == '{' && y == '}' || (y == '{' && x == '}'))
return true;
return false;
}
}
I would like general feedback and would also like to know: regarding the use of an EqualityComparer
to do something that isn't really equality-checking, is it very bad practice or is it fine?