# 双端队列

方法 效果
addFront(element) 该方法在双端队列前端添加新的元素。
addBack(element) 该方法在双端队列后端添加新的元素(实现方法和 Queue 类中的 enqueue 方法相同)。
removeFront() 该方法会从双端队列前端移除第一个元素(实现方法和 Queue 类中的 dequeue 方法相同)。
removeBack() 该方法会从双端队列后端移除第一个元素(实现方法和 Stack 类中的 pop 方法一样)。
peekFront() 该方法返回双端队列前端的第一个元素(实现方法和 Queue 类中的 peek 方法一样)。
peekBack() 该方法返回双端队列后端的第一个元素(实现方法和 Stack 类中的 peek 方法一样)。
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
class Deque{
// 一个对象来存储数据
items = {}
// 记录队头元素的指针
head = 0
// 记录队尾元素的指针
last = 0

addFront(e){
if(this.head===0){
console.log('无法在队头添加了')
return;
}
for(let i=this.last;i>=this.head;i--){
this.items[i]=this.items[i-1]
}
this.head--
}

addBack(e){
this.items[this.last] = e
this.last++
}

removeFront(){
if(this.isEmpty()){
return;
}
let res = this.items[this.head]
delete this.items[this.head]
this.head++
return res
}

removeBack(){
if(this.isEmpty()){
return;
}
let res = this.items[this.last]
delete this.items[this.last]
this.last--
return res
}

peekFront(){
return this.items[this.head]
}

peekBack(){
return this.items[this.last]
}

isEmpty(){
return this.last === this.head
}

get size(){
return this.last-this.head
}

}

回文字符串判定

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 回文字符串判定
const palindrome = function(str){
let deq = new Deque()
str = str.toLowerCase() // 都转为小写(根据判定需求决定是否需要)
for(let i of str){ // for..of 循环字符串
deq.addBack(i) // 全部加入队列中
}
while(deq.size>1){
if(deq.removeFront()!=deq.removeBack()){
return false;
}
}
return true
}

console.log(palindrome('abandon')) // false
console.log(palindrome('adfgfda')) // true
console.log(palindrome('ABccFFddFFccBa')) // true
console.log(palindrome('厂水来自上海的海上自来水厂')) //true