Palindrome Partitioning II
Implement minCut
Split a string into the fewest possible pieces so that every piece reads the same forwards and backwards, and return that minimum number of cuts (one fewer than the number of pieces).
The key observation that unlocks this is separable into two smaller questions. First: which substrings are palindromes at all? That's answered once, up front, with a small table — a single character always qualifies, and a longer stretch qualifies exactly when its two outer letters match and whatever sits between them was already found to qualify. Second, given that table, what's the fewest cuts to reach some ending position? Reaching position i for the first time as a fresh palindromic piece means some earlier position j was already reached optimally, and everything from j+1 through i forms one more valid piece — so the best answer at i is just the best answer at some valid j, plus one. Working through positions left to right means every j needed later has already been finalized.
Example 1:
Input: s = "aab"
Output: 1
Example 2:
Input: s = "abcba"
Output: 0
Example 3:
Input: s = "abcde"
Output: 4
+ 7 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ s.length ≤ 12 - ●
s consists of lowercase English letters only
s =
aab