[AlgoExpert] Balanced Brackets

Balanced Brackets

  • Time : O(n)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using namespace std;

bool balancedBrackets(string str) {
vector<char> st;
unordered_map<char, char> mp{
{')','('},
{']','['},
{'}','{'}
};
for(auto& ch : str) {
if(mp.count(ch)) {
if(!st.empty() and mp[ch] == st.back()) {
st.pop_back();
} else return false;
} else if(ch == '(' or ch == '{' or ch == '['){
st.push_back(ch);
}
}

return st.empty();
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/12/PS/AlgoExpert/balanced-brackets/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.