-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathctci-balanced-brackets.cpp
57 lines (48 loc) · 1.28 KB
/
ctci-balanced-brackets.cpp
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Stacks: Balanced Brackets
// Given a string containing three types of brackets, determine if it is balanced.
//
// https://www.hackerrank.com/challenges/ctci-balanced-brackets/problem
//
#include <bits/stdc++.h>
using namespace std;
bool is_balanced(const string& expression)
{
stack<char> balance;
for (auto c : expression)
{
if (c == '{' || c == '(' || c == '[')
{
balance.push(c);
}
else if (c == '}' || c == ')' || c == ']')
{
// il faut qu'il y ait au moins un bracket ouvrant
if (balance.empty())
return false;
char d = balance.top();
balance.pop();
// et que ça soit le bon
bool ok = (d == '(' && c == ')')
|| (d == '{' && c == '}')
|| (d == '[' && c == ']');
if (! ok)
return false;
}
}
// s'il reste quelque chose, ce n'est pas bien balancé
return balance.empty();
}
int main()
{
int t;
cin >> t;
for(int a0 = 0; a0 < t; a0++){
string expression;
cin >> expression;
bool answer = is_balanced(expression);
if(answer)
cout << "YES\n";
else cout << "NO\n";
}
return 0;
}