-
-
Notifications
You must be signed in to change notification settings - Fork 159
/
Copy pathbalancedBrackets.js
109 lines (87 loc) · 2.54 KB
/
balancedBrackets.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
class MyStack {
constructor() {
this.array = []; // Array is used to implement stack
}
// List of main functions of stack data structure
push(value) {
// push an element into the array
this.array.push(value);
}
pop() {
// Underflow if stack is empty
if (this.isEmpty()) {
return "Underflow";
}
return this.array.pop(); // return top most element from the stack and removes the same element
}
peek() {
return this.array[this.array.length - 1]; // return top most element from the stack without removing the element
}
// List of helper functions
isEmpty() {
return this.array.length === 0; // return true if stack is empty
}
printStack() {
let data = "";
for (let i = 0; i < this.array.length; i++)
data += this.array[i] + " ";
return data;
}
}
function isBalancedParentheses(parentheses) {
const myStack = new Stack();
if(parentheses.length === 0) return true;
if(parentheses.length === 1 || parentheses.length % 2 !== 0) return false;
for(const ch of parentheses) {
switch(ch) {
case '{':
case '(':
case '<':
case '[':
myStack.push(ch);
break;
case '}':
if(myStack.peek() === '{') {
myStack.pop();
} else {
return false;
}
break;
case ')':
if(myStack.peek() === '(') {
myStack.pop();
} else {
return false;
}
break;
case '>':
if(myStack.peek() === '<') {
myStack.pop();
} else {
return false;
}
break;
case ']':
if(myStack.peek() === '[') {
myStack.pop();
} else {
return false;
}
break;
}
}
if(myStack.isEmpty()) return true;
}
function useStack() {
let myStack = new MyStack();
console.log(myStack.isEmpty()); // false
console.log(myStack.pop()); // Underflow
myStack.push(1);
myStack.push(2);
myStack.push(3);
console.log(myStack.printStack()); // 1 2 3
console.log(myStack.peek()); // 3
console.log(myStack.pop()); // 3
console.log(myStack.printStack()); // 1 2
}
useStack();