In: Computer Science
1. Write a method called isPalindrome that accepts a string as a parameter and returns true if the string is a palindrome otherwise returns false. This method uses a stack and a Queue to test whether the given string parameter is a palindrome [ that is, whether the characters read the same both forward and backward. For example “race car”, and “Are we not drawn onward, to new era.” are Palindromes] They are palindrome sentences, not just a word. 2. If a string is a palindrome, do not print it out, just print a message that the given string is a Palindrome. If a string is not a palindrome, print the letters of the string in reverse order. 3. Your application prompts the user for the input string. 4. You must use a stack and a queue to do this. (You have to figure out how both can be used.) Any solution that does not use a stack and a queue for the palindrome checking and reversing the letters of the words of the sentence will receive a grade of 0.
Thanks for the question. Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks ===========================================================================
import java.util.ArrayDeque; import java.util.Queue; import java.util.Scanner; import java.util.Stack; public class IsPalindrome { // method returns true if the sentence is palindrome else returns false public static boolean isPalindrome(String sentence) { Stack<Character> stack = new Stack<Character>(); Queue<Character> queue = new ArrayDeque<Character>(); sentence = sentence.toUpperCase(); // convert the sentence to upper case char letter; // current letter in the sentence // iterate over each letter in the sentence add to the stack and to the queue for (int i = 0; i < sentence.length(); i++) { letter = sentence.charAt(i); // only add if its all alphabet if ('A' <= letter && letter <= 'Z') { stack.push(letter); queue.add(letter); } } // pop out the last element from stack and the first element from the queue while (!stack.isEmpty()) { // compare both are equal; if they are not equal then its not a palindrome if (stack.pop() != queue.poll()) { //System.out.println("Not a palindrome"); return false; } } //System.out.println("Its a palindrome"); return true; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter a sentence to check if its a palindrome: "); String sentence = scanner.nextLine(); boolean check = isPalindrome(sentence); if (check) { System.out.println("Its a palindrome"); } else { System.out.println("Not a palindrome"); } } }
==============================================================