forked from knaxus/problem-solving-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
29 lines (27 loc) · 775 Bytes
/
index.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
// FIND BALANCED PARENTHESIS
// FOR '[{()}]' ---->>>> BALANCED
// FOR '[{()]' ---->>>> UNBALANCED
// Time complexity : O(n) n is the length of the string provided.
function parentheses(s) {
if (typeof s !== 'string' || s.length % 2 !== 0) return false;
let i = 0;
const arr = [];
while (i < s.length) {
if (s[i] === '{' || s[i] === '(' || s[i] === '[') {
arr.push(s[i]);
} else if (s[i] === '}' && arr[arr.length - 1] === '{') {
arr.pop();
} else if (s[i] === ')' && arr[arr.length - 1] === '(') {
arr.pop();
} else if (s[i] === ']' && arr[arr.length - 1] === '[') {
arr.pop();
} else {
return 'Unbalanced';
}
i += 1;
}
if (arr.length === 0) return 'Balanced';
}
module.exports = {
parentheses,
};