Open In App

Python Program To Check String Is Palindrome Using Stack

Last Updated : 26 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

A palindrome is a sequence of characters that reads the same backward as forward. Checking whether a given string is a palindrome is a common programming task. In this article, we will explore how to implement a Python program to check if a string is a palindrome using a stack.

Example

Input: str = “geeksforgeeks” 
Output: No

Input: str = “madam” 
Output: Yes  

What is a Stack?

A stack is a collection of elements with two primary operations: push and pop. The push operation adds an element to the top of the stack, and the pop operation removes the top element. The stack follows the Last In, First Out (LIFO) principle. In Python, you can implement a stack using a list. Here is a simple example of a stack class in Python.

Syntax :

# Stack class definition

class Stack:

def __init__(self):

self.items = []

def push(self, item):

self.items.append(item)

def pop(self):

return self.items.pop() if not self.is_empty() else None

def is_empty(self):

return len(self.items) == 0

Python Program To Check String Is Palindrome Using Stack

Below, are the approach and code example of Python Program To Check String Is Palindrome Using Stack.

Approach

  • Initialize Stack: Create an empty stack to store characters during the checking process.
  • Push Characters onto Stack: Iterate through each character in the input string and push them onto the stack.
  • Pop and Compare: Pop characters from the stack and compare them with the characters in the string. If they match, continue the process; otherwise, the string is not a palindrome.
  • Repeat Until Completion: Continue popping and comparing until all characters are processed.
  • Determine Palindrome: If all characters match during the comparison, the string is a palindrome; otherwise, it is not. This approach utilizes the Last In, First Out (LIFO) nature of the stack to efficiently check for palindromes.

Example : Palindrome Using Stack

In this example below code defines a `Stack` class for basic stack operations and a function `is_palindrome` to check if a given string is a palindrome using a stack. It initializes a stack, pushes each character onto it, and then compares the characters by popping from the stack. The example usage checks if the string “radar” is a palindrome and prints the result after converting it to lowercase for case-insensitivity.

Python3




class Stack:
    def __init__(self):
        self.items = []
 
    def push(self, item):
        self.items.append(item)
 
    def pop(self):
        return self.items.pop() if not self.is_empty() else None
 
    def is_empty(self):
        return len(self.items) == 0
 
# Function to check palindrome using a stack
def is_palindrome(s):
    stack = Stack()
 
    # Push each character onto the stack
    for char in s:
        stack.push(char)
 
    # Pop characters from the stack and compare with the string
    for char in s:
        if char != stack.pop():
            return False
 
    return True
 
# Example usage
input_string = "radar"
result = is_palindrome(input_string.lower())  # Convert to lowercase for case-insensitivity
if result:
    print(f"{input_string} is a palindrome.")
else:
    print(f"{input_string} is not a palindrome.")


Output

radar is a palindrome.

Conclusion

In conclusion ,Using a stack to check if a string is a palindrome is a classic example of how data structures can be applied to solve real-world problems. The stack’s Last In, First Out behavior makes it suitable for reversing and comparing characters efficiently. Understanding and implementing such algorithms not only improves coding skills but also enhances problem-solving abilities in various programming scenarios.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads