Few days ago, I was asked to write a Parenthesis Balancing algorithm as a small test by one of the hiring company. I did it on time and have thought to share it with you guys.
The question goes as under.
Write a function which verifies parenthesis are balanced in a string. Each open parenthesis should have a corresponding close parenthesis and they should correspond correctly.
For example, the function should return true for the following strings:
- (if (any? y) sum (/1 y))
- I said (it's not (yet) complete). (she didn't listen)
The function should return false for the following strings:
- :-)
- ())(
Optional Bonus: Implement the solution as a recursive function with no mutation / side effects.
Besides the question asking for only the small parenthesis, this program can work on any kind of parenthesis like
i. < , >
ii. { , }
iii. [ , ]
All you have to do is provide the type of parenthesis as a second and third string parameter to the function.
Here goes the code:
private static bool Balanced(string input, string openParenthesis, string closedParenthesis)
{
try
{
if (input.Length > 0)
{
//Obtain first character
string firstString = input.Substring(0, 1);
//Check if it is open parenthesis
//If it is open parenthesis push it to stack
//If it is closed parenthesis pop it
if (firstString == openParenthesis)
stack.Push(firstString);
else if (firstString == closedParenthesis)
stack.Pop();
//In next iteration, chop off first string so that it can iterate recursively through rest of the string
input = input.Substring(1, input.Length - 1);
Balanced(input, openParenthesis, closedParenthesis); //this call makes the function recursive
}
if (stack.Count == 0 && !exception)
isBalanced = true;
}
catch (Exception ex)
{
exception = true;
}
return isBalanced;
}
Lets call this function to prove the test cases provided by the question:
- Balanced("(if (any? y) sum (/1 y))", "(", ")")
- Balanced("I said (it's not (yet) complete). (she didn't listen)", "(", ")")
- Balanced(":-)", "(", ")")
- Balanced("())(", "(", ")")
Output:
- true
- true
- false
- false
Good Luck
No comments:
Post a Comment