A boutique blacksmith's workshop keeps a single running log for every batch of blades it tempers. Each completed tempering cycle is written into the log as one unbroken three-letter block: H for heating the blade, Q for quenching it, and T for the final temper — always in that exact order, always as the block HQT. Because several apprentices can be mid-cycle on the same batch at once, a finished cycle's block gets spliced into whatever the log already looks like at that moment, and the apprentice doing the splicing is free to insert it at any position along the current log — at the front, at the back, or wedged in between letters already there. The log starts out completely empty and grows by zero or more such splices.
You are handed the final log for a batch. Determine whether it is possible that the log arose this way: that is, whether it can be built up from the empty string by repeatedly inserting the block HQT at some position, any number of times.
A single line containing the string s.
Print true if s could have arisen from this splicing process, or false otherwise.
s <= 50000s consists only of the characters H, Q, and T.Example 1
Input
HHQTQT
Expected
true
Explanation
Starting from the empty log, splice in one HQT cycle to get "HQT", then splice a second HQT cycle in right after the first H (between positions 1 and 2), giving "H" + "HQT" + "QT" = "HHQTQT", exactly matching the given log. Since it is achievable, the answer is true.
Example 2
Input
HQTTQH
Expected
false
Explanation
Unwind the log by repeatedly deleting an "HQT" block wherever one appears: the only occurrence of "HQT" in "HQTTQH" is at the very start, and removing it leaves "TQH", which contains no "HQT" substring anywhere and can never be unwound further. Since the log cannot be fully unwound back to empty, it could not have been built this way, so the answer is false.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →