Checking if a String is Palindrome using Stacks

[wpdm_package id=’1375′]

Algorithm:

  • Create a Stack.
  • Till the half of the string length, push the characters of the string into the stack.
  • If it is an odd string, simply ignore the middle character.
  • Till the end of the string, pop from the stack and check if the popped element is equal to the character in the string.
  • Return false if either the character doesn’t match or the stack becomes empty before the end of the string.
  • Return true if the Stack is empty at the end of the string.

[sourcecode lang=”cpp”]

int IsPalindrome(char *A)
{ int i=0;
std::stack S;
int l=strlen(A)/2;

while(i!=l)
{ S.push(A[i]);

i++;
}
if(strlen(A)%2!=0)
i++;
while(A[i])
{ if(S.empty()||A[i]!=S.top())
{
return 0;
}
S.pop();
i++;
}
return (S.empty());
}
[/sourcecode]

Leave a Reply

Your email address will not be published. Required fields are marked *