Given a string, like potatocarrot
, break it into the smallest number of substrings possible. These substrings can consist either be a single character, or one of a list of words passed as input. For example, if [carrot, potato]
was the input, the optimal way to break the string up would be [potato][carrot]
. If the list was [potat, tatocarr, rot]
, the optimal way would be [p][o][tatocarr][o][t]
.
You can take the string in any reasonable format, and the list of substrings in any reasonable format. As for output, any of the following would be examples of allowed output formats:
- Inserting characters into the string to delimit substrings (e.g.,
"potato,carrot"
or"[potato][carrot]"
) - Delimiting words, but not individual characters (e.g.,
"po[tatocarr]ot"
, but not"po,tatocarr,ot"
) - Returning an array of substrings (e.g.,
["potato", "carrot"]
)
You can assume the input strings consist of lowercase letters, and that there won't be duplicates or strings with a length of 0 or 1 in the list of substrings.
This is code-golf, so shortest answer (in bytes) per language wins.
Test cases:
STRING WORDS OPTIMAL SOLUTION
potatocarrot potato, carrot [potato][carrot]
potatocarrot pot, tatocarr, rot [p][o][tatocarr][o][t]
potatocarrot atocarr, ot [p][ot][atocarr][ot]
potatocarrot tatocarr, potato, carr [potato][carr][o][t]
purpur [p][u][r][p][u][r]
purpur carrot [p][u][r][p][u][r]
purpur pur [pur][pur]
purpur pu, rp [pu][r][pu][r] OR [pu][rp][u][r]
purpur pu, rp, urp [pu][r][pu][r] OR [pu][rp][u][r] OR [p][urp][u][r]
todoornottodo to, do, or, not [to][do][or][not][to][do]
todoornottodo tod, nott, door [t][o][door][nott][o][d][o]