I have written a simple routine to check if the number of parentheses balances, so [{}]
would return true since all parentheses which are opened are closed in the correct order. [)({}]
would return false since you cant start with a closing parentheses.
Is anyone able to improve the routine - (efficiency, readability) since I think it works for most cases ?
Here is the code.
public class Compiler
{
private Stack<char> Stack { get; set; }
public string Text { get; set; }
private char[] Parentheses { get; set; }
public Compiler()
{
Text = "";
//These are what I classify as parentheses (opening & closing)
Parentheses = new char[] { '{', '}', '(', ')', '[', ']' };
Stack = new Stack<char>();
}
private bool IsParentheses(char letter)
{
if (Parentheses.Contains(letter))
{
return true;
}
return false;
}
public bool IsParenthesesBalanced()
{
foreach (char letter in Text)
{
if (IsParentheses(letter))
{
if (IsOpeningParentheses(letter))
{
//Add to stack
Stack.Push(letter);
}
else if (Stack.Count > 0)
{
// Stack contains opening parentheses so {,(,[
// We pop elements when we find closing parenthese.
char top = Stack.Peek();
if (!IsCorrentClosingParenthese(top, letter))
{
return false;
}
Stack.Pop();
}
else
{
// Stack should we should a opening parenthese otherwise if we
// Pop when stack is empty it will throw an error.
// This handles when user provide first letter as a closing parenthese
// rather then opening so ]()[
return false;
}
}
}
if (Stack.Count == 0)
{
return true;
}
return false;
}
private bool IsOpeningParentheses(char parenthese)
{
int index = Array.IndexOf(Parentheses, parenthese);
// All opening parenthese are even position in array -
// '{', '}', '(', ')', '[', ']'
// 0 1 2 3 4 5
if (index % 2 == 0)
{
return true;
}
return false;
}
private bool IsCorrentClosingParenthese(char openingParenthese, char closingParenthese)
{
// All matching parenthese it start with opening and next is closing -
// '{', '}', '(', ')', '[', ']'
// 0 1 2 3 4 5
// We can check if the next openingIndex + 1 position is equal to closingParenthese
// In short just check next element.
int openingIndex = Array.IndexOf(Parentheses, openingParenthese);
if (Parentheses[openingIndex + 1] == closingParenthese)
{
return true;
}
return false;
}
}
Here I am using the class
var compiler = new Compiler();
compiler.Text = @"using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
/* my first program in C# */
Console.WriteLine(Hello World);
Console.ReadKey();
}
}
}";
compiler.IsParenthesesBalanced();
"1) Hallo World."
? I think you don't know yet that you (need to) care about quotes :-) \$\endgroup\$Console.WriteLine(Hello World);
is not valid C#. \$\endgroup\$