Improve the palindrome-recognition algorithm C++ source code, bleow, by adding t
ID: 3544414 • Letter: I
Question
Improve the palindrome-recognition algorithm C++ source code, bleow, by adding the first length/ 2 characters to the queue and then pushing the remaining characters onto the stack.
Palindrome:
//Tests whether a given string is a palindrome.
isPalindrome(someString: string): boolean
// Create an empty queue and an empty stack
aQueue = a new empty queue
aStack = a new empty stack
// Add each character of the string to both the queue and the stack
length = length od someString
for ( i = 1 through length)
{
nextChar = i^th character of someString
aQueue.enqueue(nextChar)
aStack.push(nextChar)
}
// Compare the queue characters with the stack characters
charactersAreEqual = true
while (aQueue is not empty and charactersAreEqual)
{
queueFront = aQueue.peekFront()
stackTop = aStack.peek()
if (queueFront equals stackTop)
{
aQueue.dequeue()
aStack.pop()
}
else
charactersAreEqual = false
}
return charactersAreEqual
Explanation / Answer
#include<iostream>
using namespace std;
#include<stack>
#include<queue>
#include<cstring>
stack<char>st;
queue<char>qu;
int main()
{char str[50];
int i,j,len,flag=0;
cout<<"enter the string to be checked:"<<endl;
cin>>str;
len=strlen(str);
for(i=0;i<len;i++)
{qu.push(str[i]);
st.push(str[i]);
}
for(i=0;i<len;i++)
{char c1=st.top();
char c2=qu.front();
if(c1!=c2)
{flag=1;
break;
}
st.pop();
qu.pop();
}
if(flag==1)
cout<<"the string is not palindrome"<<endl;
else
cout<<"the string is palindrome"<<endl;
return 0;
}