Post

Bracket match

Bracket match

Problem

This problem was asked by Facebook.

Given a string of round, curly, and square open and closing brackets, return whether the brackets are balanced (well-formed).

For example, given the string "([])[]({})", you should return true.

Given the string "([)]" or "((()", you should return false.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <string>
#include <stack>
#include <map>

using namespace std;


bool bracket_match(const string& str) {
    stack<char> st;
    map<char, char> m { {')', '('}, {']', '['}, {'}', '{'} };
    for (char c: str) {
        switch (c) {
            case '(':
            case '[':
            case '{':
                st.push(c); break;
            case ')':
            case ']':
            case '}':
                if (st.empty() || st.top() != m[c]) return false;
                st.pop();
                break;
            default:
                break;
        }
    }
    return st.empty();
}

int main() {

    cout << bracket_match("([])[]({})") << endl;
    cout << bracket_match("([)]") << endl;
    cout << bracket_match("((()") << endl;
    return 0;
}
This post is licensed under CC BY 4.0 by the author.