2018-10-12 15:37:13 -04:00
|
|
|
---
|
|
|
|
title: Balanced brackets
|
|
|
|
---
|
2019-07-24 00:59:27 -07:00
|
|
|
# Balanced brackets
|
2018-10-12 15:37:13 -04:00
|
|
|
|
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
---
|
|
|
|
## Solutions
|
2018-10-12 15:37:13 -04:00
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
<details><summary>### Solution #1 (Click to Show/Hide)</summary>
|
2019-06-26 23:23:46 +05:30
|
|
|
|
|
|
|
```js
|
|
|
|
function isBalanced(str) {
|
2019-07-24 00:59:27 -07:00
|
|
|
if (str === "") return true;
|
2019-06-26 23:23:46 +05:30
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
str = str.split("");
|
2019-06-26 23:23:46 +05:30
|
|
|
let stack = [];
|
|
|
|
for (let i = 0; i < str.length; i++) {
|
2019-07-24 00:59:27 -07:00
|
|
|
if (str[i] === "[") {
|
|
|
|
stack.push("[");
|
|
|
|
} else if (str[i] === "]" && stack[stack.length - 1] === "[") {
|
2019-06-26 23:23:46 +05:30
|
|
|
stack.pop();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return stack.length === 0;
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
#### Code Explanation
|
|
|
|
- Split the input string into individual characters & loop over them.
|
|
|
|
- Push every `[` into a stack.
|
|
|
|
- Check if the item stored on the stack is `[` when a `]` occurs. This makes it a pair & `[` can be removed from the stack.
|
|
|
|
- The brackets are balanced if there is no item present in the stack.
|
2019-07-24 00:59:27 -07:00
|
|
|
|
|
|
|
</details>
|