All problems
0227HardStringDynamic Programming

Mirror-Reading Ribbon Snips

Tracked in this browser only
Write code

Trains the technique from

LeetCode 132Palindrome Partitioning II

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A dyeing line prints a long strip of colour marks. The strip reaches the finishing bench as ribbon, a string of lowercase letters naming the dye at each point along the strip from its left end.

Call a length of ribbon mirror-reading when its marks spell the same sequence scanned from either end. The finisher may snip straight across the strip at any point between two neighbouring marks, and every piece that remains afterwards must be mirror-reading. Return the fewest snips that leaves the strip in that state. A piece holding a single mark is mirror-reading, so some number of snips always works.

Examples

Example 1

Input
ribbon = "civicap"
Output
2

Snipping after the fifth mark and again after the sixth leaves the pieces `civic`, `a` and `p`. Each of the three spells the same sequence from either end.

Example 2

Input
ribbon = "aabba"
Output
1

A single snip after the first mark leaves `a` and `abba`, and both pieces read the same from either end.

Example 3

Input
ribbon = "zzzz"
Output
0

The strip as delivered already spells the same sequence from either end, so the finisher hands it on untouched.

Constraints

  • 1 <= ribbon.length <= 2000
  • ribbon holds lowercase English letters only

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def fewest_ribbon_snips(ribbon: str) -> int:
Java
public int fewestRibbonSnips(String ribbon)
September 7
Apply