-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stack.js
81 lines (64 loc) · 1.71 KB
/
Stack.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
class Stack {
constructor(){
this.stack = []
this.head = -1;
this.maxes = []
}
push(element){
++this.head;
this.stack[this.head] = element
this.maxes.push(element)
}
pop(){
let element = this.stack[this.head]
this.maxes.splice(this.head,1)
this.stack.length -= 1;
--this.head;
return element
}
peek(){
return this.stack[this.head] || -1;
}
length(){
return this.head + 1
}
isEmpty(){
return this.head === -1;
}
hasValidParentheses(text){
let textArray = text.split('');
let parantheses = {
'[' : ']',
'(' : ')',
'{' : '}'
}
textArray.forEach((element) => {
if(parantheses[this.peek()] === element)
this.pop()
else this.push(element)
})
return this.isEmpty()
}
search(target) {
for (let x = 0; x<this.head; x++){
if (this.stack[x] === target) return x
}
return -1;
}
}
let stack = new Stack([]);
// console.log('push 9 ', stack.push(9))
// console.log('push 10', stack.push(10))
// console.log('pop ', stack.pop())
// console.log('push 1 ', stack.push(1))
// console.log('length', stack.length())
// console.log('isEmpty', stack.isEmpty())
// console.log('peek', stack.peek())
// console.log('searching for 10', stack.search(10))
// console.log('pop ', stack.pop())
// console.log('pop ', stack.pop())
// console.log('isEmpty', stack.isEmpty())
// console.log('peek', stack.peek())
// console.log('max', stack.max())
// console.log(stack)
console.log(stack.hasValidParentheses('()[{}]'))