-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.js
More file actions
81 lines (65 loc) · 1.44 KB
/
Copy pathstack.js
File metadata and controls
81 lines (65 loc) · 1.44 KB
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
console.log('Problem 1 — Valid Parentheses (Basic)');
function isValid(s) {
let stack = [];
let map = { ')': '(', ']': '[', '}': '{' };
for (let c of s) {
if (c == '(' || c == '[' || c == '{') {
stack.push(c);
} else {
if (stack.pop() !== map[c]) {
return false;
}
}
}
return stack.length === 0;
}
console.log(isValid('()[]{}')); // true
console.log(isValid('([)]')); // false
console.log(isValid('{[]}')); // true
console.log('Problem 2 — Min Stack (Basic)');
class MinStack {
constructor() {
this.stack = [];
this.minStack = [];
}
push(x) {
this.stack.push(x);
let min =
this.minStack.length === 0
? x
: Math.min(x, this.minStack[this.minStack.length - 1]);
this.minStack.push(min);
}
pop() {
this.stack.pop();
this.minStack.pop();
}
peek() {
return this.stack[this.stack.length - 1];
}
getMin() {
return this.minStack[this.minStack.length - 1];
}
}
let ms = new MinStack();
ms.push(5);
ms.push(3);
ms.push(7);
console.log(ms.getMin()); // 3
// ms.pop();
// ms.pop();
// console.log(ms.getMin()); // 5
console.log(ms.peek());
console.log('Problem 3 — Reverse a String using Stack (Basic)');
function reverseString(s) {
let stack = [];
for (let c of s) {
stack.push(c);
}
let result = '';
while (stack.length > 0) {
result += stack.pop();
}
return result;
}
console.log(reverseString('hello')); // "olleh"