Data Structures and Algorithms (8) - deque Dueue

  • Deque defined basis

A a set a data orderly, queue similar, but having two ends, referred to as a head end and a trailing end, the deque data may be added to the first team from the tail may be added, the data items may be removed from both ends . (It integrates the ability to stack and queue)

  • Deque abstract data types
And () Create a deque
addFront(item) The item added to the first team
addRear(item) The item added to the tail
removeFront() The first data item is removed from the team, the return value of the removed items
removeRear() Removing items from the tail, the return value of the removed item
isEmpty() Return is empty
size() Returns the data items included in the number deque

python establish their own Deque:

 1 class Deque:
 2     def __init__(self):
 3         self.items = []
 4     def isEmpty(self):
 5         return self.items == []
 6     def addFront(self,item):
 7         self.items.append(item)
 8     def addRear(self,item):
 9         self.items.insert(0,item)
10     def removeFront(self):
11         return self.items.pop() #时间复杂度O(1)
12     def removeRear(self):
13         returnself.items.pop (0) # time complexity of O (n-) 
14      DEF size (Self):
 15          return len (self.items)

 

  • Application deque
  1. Palindrome word judgment

Palindromic words: The 'abcdedcba' string so symmetrical around.

Ideas: The first term determines the desired deque added, and then were removed from both ends simultaneously determines whether the same character, until the remaining deque 0 or 1 characters.

Code:

 

. 1  from the deque Import the Deque
 2  
. 3  DEF palchecker (aString):
 . 4      '' ' 
. 5      : param aString: Characters to be judged
 . 6      : return: BOOL type
 . 7      ' '' 
. 8      chardeque = the Deque ()
 . 9  
10      for CH in aString:
 . 11          chardeque.addRear (CH)
 12 is      stillEqual = True
 13 is  
14      the while chardeque.size ()>. 1 and stillEqual:
 15          First = chardeque.removeFront ()
 16         last = chardeque.removeRear()
17         if first != last:
18             stillEqual = False
19     return stillEqual
20 print(palchecker('abcdedcba'))
21 print(palchecker('anshsoba'))

 

[out]
True
False

Process finished with exit code 0

Reference: https://www.bilibili.com/video/BV1QJ411w7bB?p=2 6

 

Guess you like

Origin www.cnblogs.com/yeshengCqupt/p/12602630.html