Confessions of a code junkie
 
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 kick it on DotNetKicks.com   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.
Name
E-mail
Home page

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.


 


Tags

Archive

Blogroll