Skip to content

Commit 98b27e9

Browse files
committed
feat: Solve balanced bracket
- Hackerrank
1 parent 1877d6d commit 98b27e9

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
.vscode
2+
.DS_Store

balanced-bracket.js

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/**
2+
* Hackerrank
3+
* A bracket is considered to be any one of the following characters: (, ), {,
4+
* }, [, or ]. Two brackets are considered to be a matched pair if the an
5+
* opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket
6+
* (i.e., ), ], or }) of the exact same type. There are three types of matched
7+
* pairs of brackets: [], {}, and ().
8+
* Given strings of brackets, determine whether each sequence of brackets is
9+
* balanced. If a string is balanced, return YES. Otherwise, return NO.
10+
*
11+
* Constraints:
12+
* 1. 0 <= n <= 10000
13+
* 2. 1 <= |s| <= 10000
14+
* 3. All the characters in the sequence: {, }, [, ], (, )
15+
*
16+
* This solution got 25 points
17+
* Problem link: http://hr.gs/babead
18+
*/
19+
20+
/**
21+
* @param {string} s The string which will be checked
22+
* @return {string} 'YES' or 'NO'
23+
*/
24+
// Complete the isBalanced function below.
25+
function isBalanced(s) {
26+
// Edge cases
27+
if (s.length === 0 || s.length % 2 === 1) {
28+
return 'NO';
29+
}
30+
const stack = [s.charAt(0)];
31+
for (const ch of s.slice(1)) {
32+
if (isClose(ch)) {
33+
const last = stack.pop();
34+
if (!isMatched(last, ch)) {
35+
return 'NO';
36+
}
37+
} else {
38+
stack.push(ch);
39+
}
40+
}
41+
return stack.length === 0 ? 'YES' : 'NO';
42+
}
43+
44+
/**
45+
* @param {string} ch - Character to be compared with
46+
* @return {boolean}
47+
*/
48+
function isClose(ch) {
49+
return /\}|\)|\]/i.test(ch);
50+
}
51+
52+
/**
53+
* @param {string} bracket - The first operator
54+
* @param {String} next - The next operator
55+
* @return {boolean}
56+
*/
57+
function isMatched(bracket, next) {
58+
switch (bracket) {
59+
case '(':
60+
return next === ')';
61+
case '[':
62+
return next === ']';
63+
case '{':
64+
return next === '}';
65+
default:
66+
return false;
67+
}
68+
}

0 commit comments

Comments
 (0)