A palindrome is a word or phrase that is spelled the same forward or backward. W
ID: 3675390 • Letter: A
Question
A palindrome is a word or phrase that is spelled the same forward or backward. Words like “pop” and “noon” are palindromes. A famous example is the phrase: “A man, a plan, a canal – Panama.” Or another, “Madam, I’m Adam.” For phrases, you have to ignore punctuation, spacing, and capitalization. The palindrome problem can be solved using a queue and a stack, putting characters simultaneously into a queue and onto a stack as the word or phrase is scanned character by character. Your program must accept a word or phrase as input and then use a queue and a stack to determine whether the input is a palindrome. It should then output to the user the phrase and the results. If you choose this problem then you must use a queue and a stack data structure to solve it.
Java Programming
Explanation / Answer
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Pallindrome
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner input = new Scanner(System.in);
System.out.println("Input a phrase or word.");
String phrase = input.nextLine();
System.out.println("You Entered : " + phrase);
String phraseWithLetters = phrase.replaceAll("[\W]", "").toLowerCase();
System.out.println("Converted phrase : " + phraseWithLetters);
int len = phraseWithLetters.length();
Stack stack = new Stack();
Queue queue = new LinkedList();
char temp,temp1;
boolean flag = false;
for(int i=0;i<len;i++)
{
stack.push(phraseWithLetters.charAt(i));
queue.add(phraseWithLetters.charAt(i));
}
while((!stack.isEmpty()) && (!queue.isEmpty()))
{
temp = (char)stack.pop();
temp1 = (char)queue.remove();
if(temp!=temp1)
{
flag = true;
break;
}
}
if(flag)
System.out.println(phrase + " is not a pallindrome.");
else
System.out.println(phrase + " is a pallindrome.");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.