利用python的双向队列(Deque)数据结构实现回文检测的算法

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# learn <<Problem Solving with Algorithms and Data Structures>>
# Release 3.0
# chengang882 @ 2016-12-20
# 它可以将常见的中缀表达式转换成后缀表达式,并计算这个表达示的值
# Completed implementation of a deque ADT

class Deque(object):
    def __init__(self):
        self.items = []

    def is_empty(self):
        return self.items == []

    def add_front(self, item):
        self.items.append(item)

    def add_rear(self, item):
        self.items.insert(0, item)

    def remove_front(self):
        return self.items.pop()

    def remove_rear(self):
        return self.items.pop(0)

    def size(self):
        return len(self.items)

def pal_checker(a_string):
    char_deque = Deque()

    for ch in a_string:
        char_deque.add_rear(ch)
    still_equal = True

    while char_deque.size() > 1 and still_equal:
        first = char_deque.remove_front()
        last = char_deque.remove_rear()
        if first != last:
            still_equal = False
    return still_equal

if __name__ == "__main__":
    print(pal_checker("asdlfkajldkfa"))
    print(pal_checker("radar"))

  输出:

>>>
False
True
>>>

  

上一篇:Android开发之EditText属性详解


下一篇:(转C#中Enum用法小结)