Skip to main content
Logo image

Problem Solving with Algorithms and Data Structures using Java: The Interactive Edition

Section 3.18 Palindrome Checker

An interesting problem that can be easily solved using the deque data structure is the classic palindrome problem. A palindrome is a string that reads the same forward and backward, for example, radar, toot, and madam. We would like to construct an algorithm to input a string of characters and check whether it is a palindrome.
The solution to this problem will use a deque to store the characters of the string. We will process the string from left to right and add each character to the tail of the deque. At this point, the deque will be acting very much like an ordinary queue. However, we can now make use of the dual functionality of the deque. The head of the deque will hold the first character of the string and the tail of the deque will hold the last character (see Figure 3.18.1).
Figure 3.18.1. A Deque for Palindrome Checking
Since we can remove both of the head and tail characters directly, we can compare them and continue only if they match. If we can keep matching first and the last items, we will eventually either run out of characters or be left with a deque of size 1, depending on whether the length of the original string was even or odd. In either case, the string must be a palindrome. The complete method for palindrome-checking appears in Listing 3.18.2.
Listing 3.18.2. Implementation of Palindrome Checker

Note 3.18.3.

If you want to have a double quote appear in a double-quoted string, you must escape it by using the backslash before the internal double quotes.
The test program checks to see that words with an odd number of letters (rotator) and an even number of letters (deed) are handled correctly.
You have attempted of activities on this page.