Stacks: Balanced Brackets

  • + 38 comments

    After writing several bad programs that barely passed the test cases, I was able to come up with this cool solution:

    bool is_balanced(string expression) {
      stack<char> s;
      for (char c : expression) {
        if      (c == '{') s.push('}');
        else if (c == '[') s.push(']');
        else if (c == '(') s.push(')');
        else {
          if (s.empty() || c != s.top())
            return false;
          s.pop();
        }
      }
      return s.empty();
    }