0% found this document useful (0 votes)
8 views2 pages

Ass 9

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views2 pages

Ass 9

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <iostream>

#include <stack>
#include <string>
#include <algorithm> // for transform, remove_if
using namespace std;

// Function to preprocess the string: remove spaces, punctuation, and make lowercase
string preprocessString(const string &str)
{
string cleanedString;
for (char ch :str)//for (char ch : str) is a range-based for loop in C++ that iterates over each
character in the string str. It is part of C++11 and later versions.
{
if (isalnum(ch))
{
cleanedString += tolower(ch); // only add alphanumeric characters
}
}
return cleanedString;
}

// Function to reverse the string using a stack


string reverseStringUsingStack(const string &str) {
stack<char> st; //The statement stack<char> st; in C++ declares a stack named st that will
store elements of type char.
string reversedStr;

// Push characters onto the stack


for (char ch :str) {
st.push(ch);
}

// Pop characters from the stack to get the reversed string


while (!st.empty()) {
reversedStr += st.top();
st.pop();
}

return reversedStr;
}

// Function to check if the string is a palindrome


bool isPalindrome(const string &str) {
string cleanedStr = preprocessString(str);
string reversedStr = reverseStringUsingStack(cleanedStr);

// Compare original processed string with the reversed one


return cleanedStr == reversedStr;
}

int main() {
string input;
cout << "Enter a string: ";
getline(cin, input);

// Preprocess the string and reverse it using a stack


string cleanedStr = preprocessString(input);
string reversedStr = reverseStringUsingStack(cleanedStr);

// Print the original string and reversed string


cout << "Original string (processed): " << cleanedStr << endl;
cout << "Reversed string: " << reversedStr << endl;

// Check if the input string is a palindrome


if (isPalindrome(input)) {
cout << "The string is a palindrome." << endl;
} else {
cout << "The string is not a palindrome." << endl;
}

return 0;
}

You might also like