Application Case 7 .Deque - the palindromic inspection

- palindrome detection: design procedures to detect whether a string is a palindrome.

- Palindrome: palindrome is a string, reading the same first and last characters, e.g., radar toot madam.

- Analysis: The solution to this problem would be to use deque to store character strings. We deal with string from left to right, and add each character to the end of the deque. At this point, deque like a regular queue. However, we can now take advantage of the dual function deque. The first part of the first character string stored in the deque, deque tail saves the last character. We can delete and compare last characters, only when they match to continue. If a match can last and last characters, we end up either run out of characters, or leave out the size of the deque 1, depending on the length of the original string is even or odd. In either case, the strings are palindromes.

 

 

class Dequeue():
    def __init__(self):
        self.items = []
    def addFont(self,item):
        self.items.append(item)
    def addRear(self,item):
        self.items.insert(0,item)
    def isEmpty(self):
        return self.items == []
    def removeFont(self):
        if self.isEmpty():
            return None
        else:
            return self.items.pop(0)
    
    def removeRear(self):
        if self.isEmpty():
            return None
        else:
            return self.items.pop()
    def size(self):
        return len(self.items)

 

method 1

DEF isHuiWei (S):
     # adding characters to the deque 
    Q = the Dequeue ()
     # indicates whether the string is a palindrome 
    for CH in S:
        q.addFont(ch)
        
    while q.size() > 1:
        first = q.removeFont()
        last = q.removeRear()
        if first != last:
            return False
    return True 
print( isHuiWei('aba'))
True

 

Method 2:

def palchecker(aString):
    chardeque = touch ()

    for ch in aString:
        chardeque.addRear(ch)

    stillEqual = True

    while chardeque.size() > 1 and stillEqual:
        first = chardeque.removeFront()
        last = chardeque.removeRear()
        if first != last:
            Still equal = False

    return stillEqual

print(palchecker("lsdkjfskf"))
print(palchecker("radar"))

 

Guess you like

Origin www.cnblogs.com/studybrother/p/11145348.html