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.
Comments are closed.
Nitriq is a Code Analysis Tool for .Net Developers. It helps you visualize your code and quickly find types and methods that need refactoring.
It is currently in a free public beta, but will have reasonable prices once the bugs are worked out.
I'll be using this blog to talk about .Net, C#, WPF, ASP.NET, Nitriq and MicroISVs.


RSS
Tags

Archive



Download   |   Documentation   |   Instructions   |   Support   |   Blog   |   About