Skip to content

Commit 335efcd

Browse files
add: solution for bracket-matcher🚀
1 parent beade6d commit 335efcd

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

bracket-matcher/README.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# Bracket Matcher
2+
3+
Have the function `BracketMatcher(str)` take the `str` parameter being passed and return `1` if the brackets are correctly matched and each one is accounted for. Otherwise return `0`. For example: if `str` is "(hello (world))", then the output should be `1`, but if `str` is "((hello (world))" the the output should be `0` because the brackets do not correctly match up. Only "(" and ")" will be used as brackets. If `str` contains no brackets return `1`.
4+
5+
## Examples
6+
7+
```javascript
8+
BracketMatcher('(hello (world))'); // should == 1
9+
BracketMatcher('((hello (world))'); // should == 0
10+
```
11+
12+
## Execute
13+
14+
```bash
15+
node solution.js
16+
```

bracket-matcher/solution.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
function BracketMatcher(str) {
2+
if (!str) return 1;
3+
4+
let opens = 0;
5+
for (let i = 0; i < str.length; i++) {
6+
if (str[i] === '(') opens++;
7+
if (str[i] === ')') opens--;
8+
if (opens < 0) return 1;
9+
}
10+
11+
return opens ? 0 : 1;
12+
}
13+
14+
(() => {
15+
['(hello (world))', '((hello (world))', undefined, null].forEach((str) => {
16+
console.log(str, '==', BracketMatcher(str));
17+
});
18+
})();

0 commit comments

Comments
 (0)