Fewest Cuts Into Palindromes

HardDynamic Programming≈ 50 min

A palindrome reads the same from left to right as from right to left: "noon", "a", "racecar". Given a string text, cut it into pieces so that every piece is a palindrome, and return the fewest cuts that need.

Every single letter is a palindrome, so there is always a way: at most one cut between each pair of letters.

Examples

text
text = "aab"         →  1
text = "racecar"     →  0
text = "abc"         →  2
text = "noonabbad"   →  2

"aab" becomes "aa" | "b". "racecar" is already a palindrome. "noonabbad" becomes "noon" | "abba" | "d".

Constraints

  • Between 1 and 400 lowercase letters.
  • Aim for O(n²): checking every piece by reading it is O(n³).
Sound off. Turn on for key clicks and a chime when the tests pass.Inline suggestions off. Recommended while you are learning. Turn on to complete words as you type.
Console
›Run to see what your code prints

Run checks the 4 visible cases here, in your browser. Submit runs all 9 on the judge, 5 of them hidden, and measures how your solution scales.