-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack-dynamic-array.js
More file actions
105 lines (78 loc) · 1.93 KB
/
stack-dynamic-array.js
File metadata and controls
105 lines (78 loc) · 1.93 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
class Stack {
constructor(){
this.stack = [];
}
isEmpty(){
return this.stack.length == 0;
}
size(){
return this.stack.length;
}
push(item){
this.stack.push(item);
}
pop(){
if(this.isEmpty()){
throw new Error('Stack is empty');
}
return this.stack.pop();
}
peek(){
if(this.isEmpty()){
throw new Error('Stack is empty');
}
return this.stack[this.stack.length - 1];
}
}
function reverseString(mystr){
let s = new Stack();
for(let i = 0; i < mystr.length; i++){
let c = mystr.charAt(i);
s.push(c);
}
let reversed = '';
while(!s.isEmpty()){
reversed += s.pop();
}
return reversed;
}
let res = reverseString('This string will be reversed ....');
console.log(res);
console.log('-----------------------------------------------');
function balancedSymbols(str){
let s = new Stack();
for(let i = 0; i < str.length; i++){
let c = str.charAt(i);
if('([{'.indexOf(c) != -1){
s.push(c);
}
else if(')]}'.indexOf(c) != -1){
if(s.isEmpty()){
return false;
}
else if('([{'.indexOf(s.peek()) == ')]}'.indexOf(c)){
s.pop();
}
}
}
return s.isEmpty();
}
console.log(balancedSymbols('{{([][])}()}'));
console.log(balancedSymbols('[{()]'));
console.log('-----------------------------------------------');
function baseConverter(dec, base){
let stack = new Stack();
let digits = '0123456789ABCDEF';
while(dec > 0){
stack.push(digits[dec % base]);
dec = Math.floor(dec / base);
}
res = '';
while(!stack.isEmpty()){
res += stack.pop();
}
return res;
}
console.log(baseConverter(25,8)) // 31
console.log(baseConverter(256,16)) // 100
console.log(baseConverter(26,26)) // 10