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 rear 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 front of the deque will hold the first character of the string and the rear of the deque will hold the last character (see Figure 2).

Figure 2: A Deque

Since we can remove both of them 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 function for palindrome-checking appears in ActiveCode 1.

Q-1: Drag each data structure to its corresponding ordering principle This is feedback.
• Stack
• last-in first-out
• Deque
• mixed depending upon input order
• Queue
• first-in first-out
Q-2: Click on the cause of a syntax error in the following code.Remember how we declare variables
deque<int> d;
d.push_back("Zebra");
d.push_front("Turtle");
d.push_front("Panda");
d.push_back("Catfish");
d.push_back("Giraffe");

Q-3: If you add five items to your code in this order “potato”, “rutabaga”, “avocado”, “squash”, “eggplant” which structure would take the least steps to retrieve “rutabaga”?

• Deque
• Yes, but it is not the only option.
• Stack
• No, a stack would pop from the top, thus having more entries in the way before it gets to rutabega.
• Queue
• Yes, but it is not the only option.
• Both B & C
• One of these two would be correct, but the other would not.
• Both A & C
• Correct!