使用棧檢查字串是否為迴文 Python 程式


當需要使用棧資料結構檢查字串是否為迴文時,會建立一個棧類,並定義 push 和 pop 方法來新增和刪除棧中的值。另一個方法檢查棧是否為空。

下面是相同內容的演示 -

示例

 線上演示

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

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

   def push_val(self, data):
      self.items.append(data)

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

my_instance = Stack_structure()
text_input = input('Enter the string... ')

for character in text_input:
   my_instance.push_val(character)

reversed_text = ''
while not my_instance.check_empty():
   reversed_text = reversed_text + my_instance.pop_val()

if text_input == reversed_text:
   print("The string is a palindrome")
else:
print("The string isn't a palindrome")

輸出

Enter the string... MalayalaM
The string is a palindrome

解釋

  • 定義了一個名為“Stack_structure”的類,其中包含“init”方法。

  • 此方法初始化一個空列表。

  • 定義了另一個名為“check_empty”的方法,該方法檢查棧是否為空。

  • 定義了另一個名為“push_val”的方法,該方法將元素新增到棧中。

  • 定義了另一個名為“pop_val”的方法,該方法從棧中刪除元素。

  • 定義了此“Stack_structure”的一個例項。

  • 從使用者處獲取字串。

  • 對其進行迭代,並在其上呼叫“check_empty”方法。

  • 定義另一個空字串,並反轉字串。

  • 此反轉後的字串儲存在空字串中。

  • 比較此反轉後的字串和來自使用者的字串。

  • 如果它們相同,則表示它是迴文。

  • 否則,它不是迴文。

  • 在控制檯上顯示相關輸出。

更新於: 2021年4月14日

853 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

立即開始
廣告