-
Notifications
You must be signed in to change notification settings - Fork 0
/
deque-circular-fixed-size-array.js
108 lines (93 loc) · 2.21 KB
/
deque-circular-fixed-size-array.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
108
class Deque {
constructor(capacity = 10){
this.capacity = capacity;
this.deque = new Array(this.capacity);
this.first = -1;
this.last = -1;
this.length = 0;
}
isEmpty(){
return this.length == 0;
}
isFull(){
return (this.last + 1) % this.capacity == this.first;
}
size(){
return this.length;
}
addFirst(item){
if(this.isFull()){
throw new Error('Deque is full');
}
if(this.first == -1){
this.first = this.last = 0;
}
else if(this.first == 0){
this.first = this.capacity - 1;
}
else{
this.first--;
}
this.deque[this.first] = item;
this.length++;
}
addLast(item){
if(this.isFull()){
throw new Error('Deque is full');
}
if(this.first == -1){
this.first = this.last = 0;
}
else{
this.last = (this.last + 1) % this.capacity;
}
this.deque[this.last] = item;
this.length++;
}
removeFirst(){
if(this.isEmpty()){
throw new Error('Deque is empty');
}
let item = this.deque[this.first];
if(this.first == this.last){
this.first = this.last = -1;
}
else{
this.first = (this.first + 1) % this.capacity;
}
this.length--;
return item;
}
removeLast(){
if(this.isEmpty()){
throw new Error('Deque is empty');
}
let item = this.deque[this.last];
if(this.first == this.last){
this.first = this.last = -1;
}
else if(this.last == 0){
this.last = this.capacity - 1;
}
else{
this.last--;
}
this.length--;
return item;
}
}
function isPalindrome(string){
d = new Deque(string.length);
for(s of string){
d.addLast(s);
}
while(d.size() > 1){
if(d.removeFirst() != d.removeLast()){
return false;
}
}
return true;
}
console.log(isPalindrome('kayak'));
console.log(isPalindrome('kayyak'));
console.log(isPalindrome('kaykak'));