Ride-hailing app~30 min2s · 256 MBtarget O(n^2) time, O(n^2) spacedp
A rides app decorates its pickup stations with slogans printed on banner tiles. A tile looks best when its letters read the same forwards and backwards, and a tile with only one or two letters looks lost. So every tile must be symmetric and have at least k letters.
Each cut between two tiles costs a fixed fee. Your team lead asks for the smallest number of cuts that splits a slogan into valid tiles, or a sign that it cannot be done.
Write fewest_tile_cuts(slogan, k).
slogan is a non-empty string of lowercase letters. A cut separates two neighbouring letters.k letters.-1 if no way of cutting works.Input: slogan = "aabbbccbb", k = 2
Output: 3Let pieces[j] be the fewest pieces for the first j letters, with pieces[0] = 0. For each j, try every last piece that is a palindrome of at least 2 letters, and add 1 to the pieces before it.
Letters used j |
Prefix | Last piece that gives the best value | pieces[j] |
|---|---|---|---|
| 1 | a |
none: a piece needs 2 letters | none |
| 2 | aa |
aa |
1 |
| 3 | aab |
none | none |
| 4 | aabb |
bb |
2 |
| 5 | aabbb |
bbb |
2 |
| 6 | aabbbc |
none | none |
| 7 | aabbbcc |
cc |
3 |
| 8 | aabbbccb |
bccb |
3 |
| 9 | aabbbccbb |
bb |
4 |
The whole slogan needs 4 pieces, so 3 cuts: aa, bbb, cc, bb.
Input: slogan = "abc", k = 2
Output: -1No piece of 2 or more letters is a palindrome, and the whole slogan is not one either.
Input: slogan = "racecar", k = 3
Output: 0The whole slogan is a palindrome with 7 letters, so no cut is needed.
1 ≤ length of slogan ≤ 1200slogan has only lowercase letters a to z1 ≤ k ≤ 1200A slogan of n letters has n - 1 places to cut, so there are 2^(n-1) ways to cut it. For n = 1200 that is far beyond any machine.
An algorithm that takes about n^2 steps does 1.4 x 10^6 steps, which is fast. A table with n^2 entries fits in the memory limit. The answer is at most n, so a 32-bit integer holds it.