In: Computer Science
In C++ Valid Palindrome
In this assignment, you need to implement a bool isPalindrome(string s) function. Given a string s, isPalindrome(s) can determine if s is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: for the purpose of this problem, we define empty string as valid palindrome.
Example 1: Input: ”A man, a plan, a canal: Panama” Output: true
Example 2: Input: ”race a car” Output: false
Requirement: There are many methods to check if a string is a palindrome or not. In this assignment, you need to use stack AND queue to in your implementation.
Suggestions: You don’t need to create the stack and queue classes by yourself. You can use the stack and queue implemention provided on Blackboard or use STL directly.
Consider all possible cases.
code:
#include<iostream>
#include<string>
#include<stack>
#include<queue>
#include<cctype>
using namespace std;
bool isPalindrome(string s)
{
stack<char> st;
queue<char> qu;
for(int i=0;i<s.length();i++)//looping over each character of
the string
{
if((s[i]>='A'&&s[i]<='Z')||(s[i]>='a'&&s[i]<='z')||(s[i]>='0'&&s[i]<='9'))//pushing
only alphanumeric characters
{
//tolower is used to handle all possible usecases, as any character
will be converted to lower case
st.push(tolower(s[i]));//pushing data to stack, which gives string
in reverse order when popped
qu.push(tolower(s[i]));//pushing data to queue, which gives string
in same order when popped
}
}
while(!st.empty()&&!qu.empty()&&st.top()==qu.front())//checking
for palindrome
{
st.pop();//removing the seen elements from stack
qu.pop();//removing the seen elements from queue
}
if(st.empty()&&qu.empty())//If queue and stack is empty
then it means the string is a palindrome
{
return true;
}
return false;
}
int main()
{
string s;
getline(cin,s);//read a complete string
if(isPalindrome(s))
cout<<"true";
else
cout<<"false";
}
Sample i/o:
Explanation:
The sample i/o is presented here and the explanation for each line is presented in the code. STL is used for implementation of the queue and stack
**please upvote if you like the answer