Nitriq is a product by
Home
|
Console Edition
|
Features
|
Getting Started
|
Documentation
|
Support
|
Blog
|
About
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
Comments are closed.
Click
Download Nitriq Now
for download options on the
NimblePros download page.
RSS
Tags
Atomiq
Blend
CopyPasteKiller
Design
Flamebait
Hacker News
IADNUG
Nitriq
Projects
Stuff
Tips and Tricks
Wishlist
XAML
Archive
September, 2010 (1)
July, 2010 (2)
June, 2010 (2)
May, 2010 (1)
April, 2010 (1)
March, 2010 (1)
November, 2009 (1)
October, 2009 (5)
September, 2009 (1)
August, 2009 (1)
July, 2009 (1)
June, 2009 (1)
May, 2009 (1)
April, 2009 (2)
March, 2009 (1)
February, 2009 (2)
January, 2009 (1)
October, 2008 (1)
September, 2008 (1)
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)