forked from knaxus/problem-solving-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
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