Question: IN JAVA 1 5 . 8 LAB: Palindrome ( Deque ) lab activity A palindrome is a string that reads the same backwards and forwards.

IN JAVA
15.8 LAB: Palindrome (Deque)
lab activity
A palindrome is a string that reads the same backwards and forwards. Use a deque to implement a program that tests whether a line of text is a palindrome. The program reads a line, then outputs whether the input is a palindrome or not.
Ex: If the input is:
senile felines!
the output is:
Yes, "senile felines!" is a palindrome.
Ex: If the input is:
rotostor
the output is:
No, "rotostor" is not a palindrome.
Ignore punctuation and spacing. Assume all alphabetic characters will be lowercase.
Special case: A one-character string is a palindrome.
provided code;
LabProgram.java
#include
#include
#include // Needed for tolower() and isalpha() functions
using namespace std;
int main(){
string line;
getline(cin, line); // Read the entire line of input
// Preprocess the input: remove non-alphabetic characters and convert to lowercase
deque dq;
for (char c : line){
if (isalpha(c)){// Check if the character is alphabetic
dq.push_back(tolower(c)); // Convert to lowercase and add to the deque
}
}
// Check if the string is a palindrome
bool is_palindrome = true;
while (dq.size()>1){// Continue until the deque is empty or contains a single character
if (dq.front()!= dq.back()){// Compare the front and the back characters
is_palindrome = false; // Set to false if any pair doesn't match
break;
}
dq.pop_front(); // Remove the front character
dq.pop_back(); // Remove the back character
}
// Output the result
if (is_palindrome){
cout << "Yes, \""<< line <<"\" is a palindrome." << endl;
} else {
cout <<"No,\""<< line <<"\" is not a palindrome." << endl;
}
return 0;
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!