-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathis-balance.js
40 lines (35 loc) · 865 Bytes
/
is-balance.js
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
/**
* Balanced brackets
*
* Determine whether a generated string of brackets is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
*
* Examples:
* (empty) true
* [] true
* ][ false
* [][] true
* ][][ false
* []][[] false
* [[[[]]]] true
*/
function isBalanced (str) {
let bal = 0;
for (let i = 0; i < str.length; i++) {
if (str.charAt(i) === "[") {
bal += 1;
} else {
bal -= 1;
}
if (bal < 0) {
return false;
}
}
return true;
}
console.log(isBalanced('') === true);
console.log(isBalanced('[]') === true);
console.log(isBalanced('))][') === false);
console.log(isBalanced('[][]') === true);
console.log(isBalanced('))][][') === false);
console.log(isBalanced('[]][[]') === false);
console.log(isBalanced('[[[[]]]]') === true);