Open In App

Check whether the given string is Palindrome using Stack

Last Updated : 13 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given string str, the task is to find whether the given string is a palindrome or not using a stack.

Examples:  

Input: str = “geeksforgeeks” 
Output: No
Input: str = “madam” 
Output: Yes  

Approach:  

  • Find the length of the string say len. Now, find the mid as mid = len / 2.
  • Push all the elements till mid into the stack i.e. str[0…mid-1].
  • If the length of the string is odd then neglect the middle character.
  • Till the end of the string, keep popping elements from the stack and compare them with the current character i.e. string[i].
  • If there is a mismatch then the string is not a palindrome. If all the elements match then the string is a palindrome.

Below is the implementation of the above approach: 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function that returns true
// if string is a palindrome
bool isPalindrome(string s)
{
    int length = s.size();
 
    // Creating a Stack
    stack<char> st;
 
    // Finding the mid
    int i, mid = length / 2;
 
    for (i = 0; i < mid; i++) {
        st.push(s[i]);
    }
 
    // Checking if the length of the string
    // is odd, if odd then neglect the
    // middle character
    if (length % 2 != 0) {
        i++;
    }
   
    char ele;
    // While not the end of the string
    while (s[i] != '\0')
    {
         ele = st.top();
         st.pop();
 
    // If the characters differ then the
    // given string is not a palindrome
    if (ele != s[i])
        return false;
        i++;
    }
 
return true;
}
 
// Driver code
int main()
{
    string s = "madam";
 
    if (isPalindrome(s)) {
        cout << "Yes";
    }
    else {
        cout << "No";
    }
 
    return 0;
}
 
// This Code is Contributed by Harshit Srivastava


C




// C implementation of the approach
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
char* stack;
int top = -1;
 
// push function
void push(char ele)
{
    stack[++top] = ele;
}
 
// pop function
char pop()
{
    return stack[top--];
}
 
// Function that returns 1
// if str is a palindrome
int isPalindrome(char str[])
{
    int length = strlen(str);
 
    // Allocating the memory for the stack
    stack = (char*)malloc(length * sizeof(char));
 
    // Finding the mid
    int i, mid = length / 2;
 
    for (i = 0; i < mid; i++) {
        push(str[i]);
    }
 
    // Checking if the length of the string
    // is odd, if odd then neglect the
    // middle character
    if (length % 2 != 0) {
        i++;
    }
 
    // While not the end of the string
    while (str[i] != '\0') {
        char ele = pop();
 
        // If the characters differ then the
        // given string is not a palindrome
        if (ele != str[i])
            return 0;
        i++;
    }
 
    return 1;
}
 
// Driver code
int main()
{
    char str[] = "madam";
 
    if (isPalindrome(str)) {
        printf("Yes");
    }
    else {
        printf("No");
    }
 
    return 0;
}


Java




// Java implementation of the approach
class GFG
{
static char []stack;
static int top = -1;
 
// push function
static void push(char ele)
{
    stack[++top] = ele;
}
 
// pop function
static char pop()
{
    return stack[top--];
}
 
// Function that returns 1
// if str is a palindrome
static int isPalindrome(char str[])
{
    int length = str.length;
 
    // Allocating the memory for the stack
    stack = new char[length * 4];
 
    // Finding the mid
    int i, mid = length / 2;
 
    for (i = 0; i < mid; i++)
    {
        push(str[i]);
    }
 
    // Checking if the length of the String
    // is odd, if odd then neglect the
    // middle character
    if (length % 2 != 0)
    {
        i++;
    }
 
    // While not the end of the String
    while (i < length)
    {
        char ele = pop();
 
        // If the characters differ then the
        // given String is not a palindrome
        if (ele != str[i])
            return 0;
        i++;
    }
 
    return 1;
}
 
// Driver code
public static void main(String[] args)
{
    char str[] = "madam".toCharArray();
 
    if (isPalindrome(str) == 1)
    {
        System.out.printf("Yes");
    }
    else
    {
        System.out.printf("No");
    }
}
}
 
// This code is contributed by PrinciRaj1992


Python3




# Python3 implementation of the approach
stack = []
top = -1
 
# push function
def push(ele: str):
    global top
    top += 1
    stack[top] = ele
 
# pop function
def pop():
    global top
    ele = stack[top]
    top -= 1
    return ele
 
# Function that returns 1
# if str is a palindrome
def isPalindrome(string: str) -> bool:
    global stack
    length = len(string)
 
    # Allocating the memory for the stack
    stack = ['0'] * (length + 1)
 
    # Finding the mid
    mid = length // 2
    i = 0
    while i < mid:
        push(string[i])
        i += 1
 
    # Checking if the length of the string
    # is odd, if odd then neglect the
    # middle character
    if length % 2 != 0:
        i += 1
 
    # While not the end of the string
    while i < length:
        ele = pop()
 
        # If the characters differ then the
        # given string is not a palindrome
        if ele != string[i]:
            return False
        i += 1
    return True
 
# Driver Code
if __name__ == "__main__":
 
    string = "madam"
 
    if isPalindrome(string):
        print("Yes")
    else:
        print("No")
 
# This code is contributed by
# sanjeev2552


C#




// C# implementation of the approach
using System;
 
class GFG
{
 
static char []stack;
static int top = -1;
 
// push function
static void push(char ele)
{
    stack[++top] = ele;
}
 
// pop function
static char pop()
{
    return stack[top--];
}
 
// Function that returns 1
// if str is a palindrome
static int isPalindrome(char []str)
{
    int length = str.Length;
 
    // Allocating the memory for the stack
    stack = new char[length * 4];
 
    // Finding the mid
    int i, mid = length / 2;
 
    for (i = 0; i < mid; i++)
    {
        push(str[i]);
    }
 
    // Checking if the length of the String
    // is odd, if odd then neglect the
    // middle character
    if (length % 2 != 0)
    {
        i++;
    }
 
    // While not the end of the String
    while (i < length)
    {
        char ele = pop();
 
        // If the characters differ then the
        // given String is not a palindrome
        if (ele != str[i])
            return 0;
        i++;
    }
    return 1;
}
 
// Driver code
public static void Main(String[] args)
{
    char []str = "madam".ToCharArray();
 
    if (isPalindrome(str) == 1)
    {
        Console.Write("Yes");
    }
    else
    {
        Console.Write("No");
    }
}
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
// Javascript implementation of the approach
 
// Function that returns true
// if string is a palindrome
function isPalindrome(s)
{
    var length = s.length;
 
    // Creating a Stack
    var st = [];
 
    // Finding the mid
    var i, mid = parseInt(length / 2);
 
    for (i = 0; i < mid; i++) {
        st.push(s[i]);
    }
 
    // Checking if the length of the string
    // is odd, if odd then neglect the
    // middle character
    if (length % 2 != 0) {
        i++;
    }
   
    var ele;
    // While not the end of the string
    while (i != s.length)
    {
         ele = st[st.length-1];
         st.pop();
 
    // If the characters differ then the
    // given string is not a palindrome
    if (ele != s[i])
        return false;
        i++;
    }
 
return true;
}
 
// Driver code
var s = "madam";
if (isPalindrome(s)) {
    document.write( "Yes");
}
else {
    document.write( "No");
}
 
</script>


Output: 

Yes

 

Time Complexity: O(N).
Auxiliary Space: O(N). 



Previous Article
Next Article

Similar Reads

Python Program To Check String Is Palindrome Using Stack
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: NoInput: str = “madam” Out
3 min read
How to check whether a passed string is palindrome or not in JavaScript ?
In this article, we are given a string, our task is to find string is palindrome or not. A palindrome is a series of numbers, strings, or letters that, when read from right to left and left to right, match each other exactly or produce the same series of characters. in simple words when number strings or characters are inverted and still provide th
4 min read
Check whether the given floating point number is a palindrome
Given a floating-point number N, the task is to check whether it is palindrome or not. Input: N = 123.321 Output: YesInput: N = 122.1 Output: No Approach: First, convert the given floating-point number into a character array.Initialize the low to first index and high to the last index.While low &lt; high: If the character at low is not equal to the
4 min read
Check if given Binary String can be made Palindrome using K flips
Given a binary string str, the task is to determine if string str can be converted into a palindrome in K moves. In one move any one bit can be flipped i.e. 0 to 1 or 1 to 0. Examples: Input: str = "101100", K = 1Output: YESExplanation: Flip last bit of str from 0 to 1. Input: str = "0101101", K = 2Output: NOExplanation: Three moves required to mak
5 min read
Check whether given string can be generated after concatenating given strings
Given three strings str, A and B. The task is to check whether str = A + B or str = B + A where + denotes concatenation. Examples: Input: str = "GeeksforGeeks", A = "Geeksfo", B = "rGeeks" Output: Yes str = A + B = "Geeksfo" + "rGeeks" = "GeeksforGeeks"Input: str = "Delhicapitals", B = "Delmi", C = "capitals" Output: No Approach: If len(str) != len
11 min read
Stack Permutations (Check if an array is stack permutation of other)
A stack permutation is a permutation of objects in the given input queue which is done by transferring elements from the input queue to the output queue with the help of a stack and the built-in push and pop functions. The rules are: Only dequeue from the input queue.Use inbuilt push, and pop functions in the single stack.Stack and input queue must
15+ min read
Count all palindrome which is square of a palindrome
Given two positive integers L and R (represented as strings) where [Tex]1\leq L \leq R\leq10^{18} [/Tex]. The task is to find the total number of super-palindromes in the inclusive range [L, R]. A palindrome is called super-palindrome if it is a palindrome and also square of a palindrome. Examples: Input: L = "4", R = "1000" Output: 4 Explanation:
10 min read
Sentence Palindrome (Palindrome after removing spaces, dots, .. etc)
Write a program to check if a sentence is a palindrome or not. You can ignore white spaces and other characters to consider sentences as a palindrome. Examples: Input : str = "Too hot to hoot." Output : Sentence is palindrome. Input : str = "Abc def ghi jklm." Output : Sentence is not palindrome. Note: There may be multiple spaces and/or dots betwe
12 min read
Check if String formed by first and last X characters of a String is a Palindrome
Given a string str and an integer X. The task is to find whether the first X characters of both string str and reversed string str are same or not. If it is equal then print true, otherwise print false. Examples: Input: str = abcdefba, X = 2Output: trueExplanation: First 2 characters of both string str and reversed string str are same. Input: str =
5 min read
Python program to check if given string is vowel Palindrome
Given a string (may contain both vowel and consonant letters), remove all consonants, then check if the resulting string is palindrome or not. Examples: Input : abcuhuvmnba Output : YES Explanation : The consonants in the string "abcuhuvmnba" are removed. Now the string becomes "auua". Input : xayzuezyax Output : NO Input : bkldhgcj Output : -1 App
5 min read