-
Notifications
You must be signed in to change notification settings - Fork 269
/
index.js
47 lines (42 loc) Β· 1.24 KB
/
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
Given an expression string exp , write a program to examine whether the pairs and
the orders of β{β,β}β,β(β,β)β,β[β,β]β are correct in expression.
Example:
Input: exp = β[()]{}{[()()]()}β
Output: true
Input: exp = β[(])β
Output: false
*/
const Stack = require('../index');
function checkBalancedParenthesis(expression) {
const s = new Stack();
for (let i = 0; i < expression.length; i += 1) {
const char = expression[i];
if (char === '{' || char === '(' || char === '[') {
// If current character is a starting bracket (β(β or β{β or β[β) then push it to stack
s.push(char);
} else {
if (s.isEmpty()) {
// when we have only right parenthesis or brackets in expresion
return false;
}
if (
(char === '}' && s.peek() !== '{') ||
(char === ')' && s.peek() !== '(') ||
(char === ']' && s.peek() !== '[')
) {
return false;
}
// If the current character is a closing bracket (β)β or β}β or β]β) then pop it from stack
s.pop();
}
}
if (s.isEmpty()) {
// expression has balanced parenthesis
return true;
}
return false;
}
module.exports = {
checkBalancedParenthesis,
};