Pseudo-Banana Strings
InterviewTime limit2sMemory limit512 MB
Given a string of B, A, N, find the minimum number of character replacements that turn it into a concatenation of blocks of the form B+ANANA(NA)*.
- Level
Medium6 of 10
- Topics
- Dynamic programming, String, Implementation, Greedy
- Solved
- No attempts yet
Problem
A pseudo-banana is defined by the following rules:
- is a pseudo-banana.
- For a pseudo-banana , with prepended is also a pseudo-banana.
- For a pseudo-banana , with appended is also a pseudo-banana.
Hence every pseudo-banana has the form with integers and , and its length is .
A pseudo-banana string is a concatenation of one or more pseudo-bananas. Given a string over , and , determine the minimum number of character replacements needed to turn it into a pseudo-banana string.
Input
A string of length is given on one line. consists only of the characters , and . satisfies .
Output
Print on one line the minimum number of character replacements needed to turn the given string into a pseudo-banana string. Every input with length at least 6 admits such a string, so an answer always exists.
Hint
One pseudo-banana consists of one or more characters, followed by , followed by zero or more repetitions of . A full string is a repetition of such blocks, where after a block boundary either the starting the next block or the continuing the tail may appear.
This structure can be expressed as a deterministic finite automaton with 8 states. Matching the input against it reduces to dynamic programming that keeps, for each position, the cheapest cost of reaching every state.
