-
-
Notifications
You must be signed in to change notification settings - Fork 155
/
Copy pathbalancedBrackets.js
98 lines (80 loc) · 2.32 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
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 el of this.array)
data += el + " ";
return data;
}
}
function hasBalancedParentheses(characters) {
const myStack = new MyStack();
if(characters.length === 0) return true;
if(characters.length === 1 || characters.length % 2 !== 0) return false;
for(const ch of characters) {
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;
}
let str1 = '()[]{}<>';
let str2 = '[({<>})]';
let str3 = '([)]';
console.log(hasBalancedParentheses(str1));
console.log(hasBalancedParentheses(str2));
console.log(hasBalancedParentheses(str3));