Print a given string of A, B and C with push, pop and print on a letter stack using the fewest operations.
Medium7Dynamic programmingStackNo attempts yetTime limit5sMemory limit512 MBRoland teaches high-school math. Every day he collects hundreds of papers from his students, and for each paper he picks one letter grade: 'A', 'B', or 'C'. (Roland's students are too smart to get a 'D' or an 'F'.) Once the grades are decided, Roland hands the papers to his assistant, you. Your job is to stamp the right grade onto each paper.
The stamp you use is low-tech but it works. To print a letter, you attach the plate for that letter to the front of the stamp, dip it in ink, and press it onto the paper.
The useful part is that you do not have to remove a plate to switch letters. You can attach a new plate on top of the old one. The plates on the stamp therefore behave like a stack with these three operations.
Given a string of 'A', 'B', and 'C', find the minimum number of operations needed to print the whole string in order. The stack starts empty and must be empty again when you are done. You have an unlimited supply of plates of each kind, so you may use as many as you like in between.
For example, "ABCCBA" can be printed in 12 operations as shown below. The stack column lists the letters from the bottom up.
| Step | Operation | Printed so far | Stack |
|---|---|---|---|
| 0 | (start) | (none) | (none) |
| 1 | Push A | (none) | A |
| 2 | A | A | |
| 3 | Push B | A | AB |
| 4 | AB | AB | |
| 5 | Push C | AB | ABC |
| 6 | ABC | ABC | |
| 7 | ABCC | ABC | |
| 8 | Pop | ABCC | AB |
| 9 | ABCCB | AB | |
| 10 | Pop | ABCCB | A |
| 11 | ABCCBA | A | |
| 12 | Pop | ABCCBA | (none) |
The first line contains the number of test cases, T. Each of the next T lines contains one string S, the letters you have to print in order.
For each test case, print one line in the form "Case #x: N", where x is the test case number starting from 1 and N is the minimum number of stack operations needed to print S.