VON#
Confessions of a code junkie
RSS
Tuesday, July 22, 2008
Programming Job Interview Challenge #13 Answer
Programming Job Interview Challenge Question Week #13
Highlight the text below for the answer.
This is pretty simple, use a stack to track all open brackets and on all closed pop the stack to see if you have the correct matching bracket.
private bool AreBracketsClosedProperly(string input)
{
Stack<char> openBrackets = new Stack<char>();
foreach (char bracket in input)
{
switch (bracket)
{
case '(':
case '[':
case '<':
case '{':
openBrackets.Push(bracket);
break;
case ')':
if (openBrackets.Pop() != ')')
return false;
case ']':
if (openBrackets.Pop() != ']')
return false;
case '>':
if (openBrackets.Pop() != '>')
return false;
case '}':
if (openBrackets.Pop() != '}')
return false;
break;
}
}
if (openBrackets.Count != 0)
return false;
else
return true;
}
Tuesday, July 22, 2008 - 8:00 AM CST -
Permalink
Comments [1]
-
Tags:
Stuff
Tuesday, August 05, 2008 8:28:26 AM (Central Standard Time, UTC-06:00)
The problem with this algorithm is that if the first character is a close bracket, you'll pop an empty stack, which will throw an exception. Since that is a "legitimate" bad string, you should be return false in that case.
James Curran
Name
E-mail
Home page
Remember Me
Comment (Some html is allowed:
a@href@title, strike
) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.
Enter the code shown (prevents robots):
Live Comment Preview
All Content © 2008, Jon von Gillern
Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
Home
Tags
Blend
Design
IADNUG
Projects
Stuff
Tips and Tricks
Wishlist
Archive
August, 2008 (1)
July, 2008 (2)
June, 2008 (2)
May, 2008 (2)
March, 2008 (2)
February, 2008 (8)
January, 2008 (4)
December, 2007 (6)
November, 2007 (2)
Blogroll
Eric Sink
Javier Lozano
Jeff Atwood
Joel Spolsky
Nick Parker
Paul Graham
Scott Hanselman
Tim Gifford