簡體   English   中英

使用 Deque 檢查給定字符串是否為回文

[英]Check whether a given string is palindrome using Deque

我寫了一個 python 代碼來檢查給定的字符串是否是回文。 但是,代碼有問題。 對於每個字符串,它返回 True,即它是一個回文。 我的代碼有什么問題?

這是我的代碼:

class Deque:
    def __init__(self):
        self.items=[]
    def empty(self):
        return self.items==[]
    def push_back(self,item):
        self.items.append(item)
    def push_front(self,item):
        self.items.insert(0,item)
    def pop_back(self):
        self.items.pop()
    def pop_front(self):
        self.items.pop(0)
    def back(self):
        return self.items[-1]
    def front(self):
        return self.items[0]
    def size(self):
        return len(self.items)
    def at(self,index):
        return self.items[index]
def palcheck(string):
    D=Deque()
    for char in string:
        D.push_back(char)
    stillEqual=True
    while D.size() >1 and stillEqual:
        first=D.pop_front()
        last=D.pop_back()
        if first!=last:
            stillEqual=False
    return stillEqual

print(palcheck("lsknfjbdf"))

您的pop方法不顯式返回任何內容 - 因此它們隱式返回None

因此, if first!=last:將始終執行if None!=None:

只需更改您的 pop 方法以返回彈出的值:

def pop_back(self):
    return self.items.pop()
def pop_front(self):
    return self.items.pop(0)

要測試一個字符串是否是回文,它很簡單:

def ispalindrome(s):
  return s == s[::-1]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM