This problem can be solved with Dynamic Programming, but this practice is about Recursion. Please solve it with Recursion.
Elephants have a very good memory. Elfnt wants to train his own memory, so he decides to compress the words he has to memorize.
An encoded string is written with the following rules:
k[E] stands for the string that E stands for, repeated times. Here is a positive integer written in decimal, and E is any encoded string. For example, 3[ab] stands for ababab.2[a]bc stands for aabc.Since E is again an encoded string, brackets can be nested. For example, 2[2[abbb]c] stands for abbbabbbcabbbabbbc.
The length of an encoded string counts every character in it, including the digits and the brackets. For example, the length of 10[a] is .
If no encoded string is shorter than the word, you can choose not to encode it.
You are given words. For each word, print the length of the shortest encoded string that stands for it.
For a word s, there are three choices:
s as it is.s is some prefix repeated times, write it as k[...] and encode the prefix.s into two parts and encode each part.Choices 2 and 3 encode shorter words, so they can call the same function again. The same word will be asked for many times, so record every word you have already solved:
memo = {}
def f(x):
if x in memo:
return memo[x]
...
memo[x] = ans
return ans
The first line contains .
Each of the next lines contains one word made of lowercase English letters.
Print lines. The -th line contains one integer: the length of the shortest encoded string for the -th word.
End every line with a newline, including the last.
aaa: 3[a] has length , which is longer than the word itself, so the answer is .aaaaa: 5[a] has length .ababababcdabcd: 4[ab]cdabcd has length .elephant: nothing can be made shorter.abbbabbbcabbbabbbc: 2[2[abbb]c] has length .