Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

JAVA: A palindrome is defined as A string of characters that reads the same from

ID: 3822106 • Letter: J

Question

JAVA:

A palindrome is defined as

A string of characters that reads the same from left to right as its does from right to left

Example: Anna, Civic, Kayak, Level, Madam

To recognize a palindrome, a queue can be used in conjunction with a stack o A stack can be used to reverse the order of occurrences o A queue can be used to preserve the order of occurrences

Hints: Use Stack class in JAVA library       

https://docs.oracle.com/javase/7/docs/api/java/util/Stack.html

              Regard linked list in JAVA Library as queue

http://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html

Explanation / Answer

Hi, Please find my implementation.

import java.util.LinkedList;

import java.util.Queue;

import java.util.Scanner;

import java.util.Stack;

public class Palindrome

{

   public static void main(String[ ] args)

   {

       Scanner input = new Scanner(System.in);

      

       System.out.println("Enter string(exit to stop): ");

       String line = input.next();

       // reading line by line

       while(! "exit".equalsIgnoreCase(line)){

           // checking whether current line is palindrome or not

           System.out.println(line);

           if (isPalindrome( line )){

               System.out.println("   Yes it is a palindrome.");

           }

           else{

               System.out.println("   No this is not a palindrome.");

           }

           System.out.println("Enter string(exit to stop): ");

           line = input.next();

       }

   }

   public static boolean isPalindrome(String input)

   {

       input = input.toLowerCase();

       Queue<Character> q = new LinkedList<Character>();

       Stack<Character> s = new Stack<Character> ();

       char letter;

       int i;

       // iterating over input string

       for (i = 0; i < input.length( ); i++)

       {

           letter = input.charAt(i);

           // if current character is digit or letter then push into stack and add into queue

           if(Character.isLetterOrDigit(letter)){

               q.offer(letter);

               s.push(letter);

           }

       }

       // now pop from stack and dequeue from queue character by character and compare

       while (!q.isEmpty( ))

       {

           if (q.poll() != s.pop( ))

               return false;

       }

       return true;

   }

}

/*

Sample Output:

Enter string(exit to stop):

madam

madam

   Yes it is a palindrome.

Enter string(exit to stop):

Civic

Civic

   Yes it is a palindrome.

Enter string(exit to stop):

Kayak

Kayak

   Yes it is a palindrome.

Enter string(exit to stop):

exit

*/