forked from adamespii/daily-coding-problem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproblem_027.js
35 lines (30 loc) Β· 899 Bytes
/
problem_027.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
/**
* Checks whether string of round, curly, and square brackets are balanced
* @param {string} input
* @return {boolean}
*/
const isBalanced = (input) => {
const stack = [];
for(let i = 0; i < input.length; i++) {
const bracket = input.charAt(i);
if (bracket === '(' || bracket === '[' || bracket === '{') {
stack.push(bracket);
}
else {
const closedBracket = stack.pop();
if (closedBracket === undefined) return false;
if (!isMatch(openingBracket, closedBracket)) return false;
}
return stack.length === 0;
}
}
const isMatch = (opening, closing) => {
return (
(opening === '(' && closing === ')') ||
(opening === '[' && closing === ']') ||
(opening === '{' && closing === '}')
);
}
console.log(isBalanced("([])[]({})")); // true
console.log(isBalanced("([)]")); // false
console.log(isBalanced("((()")); // false