Posted on

Description

Solution

  • The solution is easy but inspires me with a new way to find a palindrome.
#include <iostream>
#include <vector>

using namespace std;

class Solution {
    //Write your code here
    vector<char> s;
    vector<char> q;
public:
    void pushCharacter(char c)
    {
        s.push_back(c);
    }

    void enqueueCharacter(char c)
    {
        q.push_back(c);
    }

    char popCharacter()
    {
        char ret = *prev(s.end());
        s.erase(prev(s.end()));
        return ret;
    }

    char dequeueCharacter()
    {
        char ret = *q.begin();
        q.erase(q.begin());
        return ret;
    }
};

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;
}

Leave a Reply

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