-
Notifications
You must be signed in to change notification settings - Fork 270
/
Copy pathindex.js
43 lines (37 loc) Β· 1.37 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
/**
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) {
let s = new Stack();
for (let i = 0; i < expression.length; i++) {
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;
} else 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;
} else {
return false;
}
}
console.log(checkBalancedParenthesis("{()}[]")); //true
console.log(checkBalancedParenthesis("{()}}")); //false