Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Kiểm tra chuỗi Palindrome bằng Stack trong Python

Đẩy từng ký tự vào stack, sau đó pop lần lượt để xây dựng chuỗi đảo ngược, so sánh với chuỗi gốc.

Ví dụ

class Stack_structure:
    def __init__(self):
        self.items = []
    def is_empty(self):
        return self.items == []
    def push(self, data):
        self.items.append(data)
    def pop(self):
        return self.items.pop()

st = Stack_structure()
text = input("Nhập chuỗi: ")
for ch in text:
    st.push(ch)
reversed_text = ""
while not st.is_empty():
    reversed_text += st.pop()
if text == reversed_text:
    print("Chuỗi là palindrome")
else:
    print("Chuỗi không phải palindrome")

Kết quả

Nhập chuỗi: MalayalaM
Chuỗi là palindrome

Giải thích

  • Stack LIFO -> pop ra theo thứ tự ngược lại.
  • So sánh chuỗi gốc và chuỗi đảo ngược.
  • Phân biệt chữ hoa/thường (ví dụ 'MalayalaM' đúng, 'malayalam' cũng đúng).