Hackerrank | 30 days of code | Day 18-Solution in c++| Queues-and-Stacks-hackerrank-Solution-in-c++


Hackerrank | 30 days of code | Day 18-Solution in c++| Queues-and-Stacks-hackerrank-Solution-in-c++

Hackerrank Solution 30-days-of-code

https://www.hackerrank.com/challenges/30-queues-and-stacks/problem
Day 18 Queues and Stacks Solution in Cpp
#include <iostream> #include<queue> #include<stack> using namespace std; class Solution { public: queue<char> q; stack<char> s; void pushCharacter(const char c_) { s.push(c_); } void enqueueCharacter(const char c_) { q.push(c_); } char popCharacter() { char c = s.top(); s.pop(); return c; } char dequeueCharacter() { char c = q.front(); q.pop(); return c; } }; int main() { // read the string s. string s; getline(cin, s); // create the Solution class object p. Solution obj; // push/enqueue all the characters of string s to stack. for (int i = 0; i < s.length(); i++) { obj.pushCharacter(s[i]); obj.enqueueCharacter(s[i]); } bool isPalindrome = true; // pop the top character from stack. // dequeue the first character from queue. // compare both the characters. for (int i = 0; i < s.length() / 2; i++) { if (obj.popCharacter() != obj.dequeueCharacter()) { isPalindrome = false; break; } } // finally print whether string s is palindrome or not. if (isPalindrome) { cout << "The word, " << s << ", is a palindrome."; } else { cout << "The word, " << s << ", is not a palindrome."; } return 0; }

Post a Comment

0 Comments