-
Notifications
You must be signed in to change notification settings - Fork 25
/
Brackets.cpp
71 lines (65 loc) · 1.58 KB
/
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// https://app.codility.com/programmers/lessons/7-stacks_and_queues/brackets/
//
// Task Score: 100%
// Correctness: 100%
// Performance: 100%
// Detected time complexity: O(N)
//
#include <string>
#include <stack>
using namespace std;
int solution(string &S) {
int N = S.length();
// Quick check for empty string
if ( N == 0) {
return 1;
}
// Any nested string is a pair, so odd length strings are improperly nested
if ( N%2 ) {
return 0;
}
// Go through the string:
// * Push if [ `{', '[', '(' ]
// * Pop if [ `]', '}', ')' ]
// * Return 1 if the string was closed
// This is O(N)
stack<char> nest;
char c;
for (int i=0; i<N; i++) {
switch (S[i]) {
case '{':
case '[':
case '(':
nest.push(S[i]);
break;
case '}':
c = nest.top();
nest.pop();
if ( c != '{') {
return 0;
}
break;
case ']':
c = nest.top();
nest.pop();
if ( c != '[') {
return 0;
}
break;
case ')':
c = nest.top();
nest.pop();
if ( c != '(') {
return 0;
}
break;
default: break;
}
}
// Some elements were left hanging!
if (nest.size() > 0 ) {
return 0;
}
// No errors, so good!
return 1;
}