Sample Program Using Queue: Detecting Palindromes


//  this program will read a string and determine whether it
//  is a palindrome (a string is a palindrome if it is the same
//  forwards and backwards, ignoring capitalization and
//  punctuation)

import java.util.Scanner;

public class IsPalindrome {

    public static void main(String[] args) {
        ArrayBoundedStack<Character> chstack = new ArrayBoundedStack<Character>();
        ArrayUnboundedQueue<Character> chqueue = new ArrayUnboundedQueue<Character>();
        char inchar;
        char stchar;
        char qchar;
        boolean ispalindrome;
        int i = 0;
        String instr;
        Scanner keybd = new Scanner(System.in);

//  initialize, then read string and create original and reversed
//  versions using the stack and queue
        System.out.println("Enter a line of text");
        instr = keybd.nextLine();
        while (i < instr.length()) {
            inchar = instr.charAt(i);
            if (Character.isLetter(inchar)) {
                chstack.push(Character.toLowerCase(inchar));
                chqueue.enqueue(Character.toLowerCase(inchar));
            }
            i++;
        }

//  get one character at a time from each string and compare them. if
//  they ever differ then the string was not a palindrome
//
//  only need to check for stack to be empty because we know stack and
//  queue contain the same number of elements
        ispalindrome = true;
        while (!chstack.isEmpty() && ispalindrome) {
            stchar = chstack.top();
            chstack.pop();
            qchar = chqueue.dequeue();
            if (stchar != qchar)
                ispalindrome = false;
         }    //  end while

//  check ispalindrome to find out whether the two strings matched
//  everywhere
      if (ispalindrome)
          System.out.println("The string is a palindrome\n");
      else
          System.out.println("The string is not a palindrome\n");
    }
}

Sample Output

Enter a line of text
Racecar!
The string is a palindrome

Enter a line of text
Able was I, ere I saw Elba
The string is a palindrome

Enter a line of text
rathstar
The string is not a palindrome



Email Me | Office Hours | My Home Page | Department Home | MCC Home Page