Cracking the Coding Interview: Stacks – Balanced Brackets

Here’s my solution to the challenge: https://www.hackerrank.com/challenges/ctci-balanced-brackets

bool is_balanced(string expression) {
    stack  s;
    for (int i = 0; i < expression.length(); i++) {
        if (expression[i] == '{')
            s.push('}');
        else if (expression[i] == '[')
            s.push(']');
        else if (expression[i] == '(')
            s.push(')');
        else {
            if (s.empty() || expression[i] != s.top())
                return false;
            s.pop();
        }
    }
    return s.empty();
}

All my solutions to HackerRank challenges can be found here: https://github.com/sdulaney/hackerrank

Leave a Comment