<p>Given a string <code>s</code>, partition <code>s</code> such that every <span data-keyword="substring-nonempty">substring</span> of the partition is a <span data-keyword="palindrome-string">palindrome</span>.</p>

<p>Return <em>the <strong>minimum</strong> cuts needed for a palindrome partitioning of</em> <code>s</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;aab&quot;
<strong>Output:</strong> 1
<strong>Explanation:</strong> The palindrome partitioning [&quot;aa&quot;,&quot;b&quot;] could be produced using 1 cut.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;a&quot;
<strong>Output:</strong> 0
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;ab&quot;
<strong>Output:</strong> 1
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= s.length &lt;= 2000</code></li>
	<li><code>s</code> consists of lowercase English letters only.</li>
</ul>

class Solution:
  def getIdToPalindomeEndIds(self, s: str) -> Dict:
    id_to_end_ids = {}
    for i in range(len(s)):
      id_to_end_ids[i] = []
      # odd-length palindromes, consecutive characters center
      self.expandPalindromesAroundCenter(s, i, i, id_to_end_ids)
      # even-length palindromes, consecutive characters center
      self.expandPalindromesAroundCenter(s, i, i + 1, id_to_end_ids)
    return id_to_end_ids

  def expandPalindromesAroundCenter(self, ss: str, lo: int, hi: int, id_to_end_ids: Dict):
    while lo >= 0 and hi < len(ss):
      if ss[lo] != ss[hi]:
        break  # the first and last characters don't match!
      id_to_end_ids[lo].append(hi)
      # expand around the center
      lo -= 1
      hi += 1
    return

  def minCut(self, s: str) -> int:
    id_to_end_ids = self.getIdToPalindomeEndIds(s)
    # // dp[i] tracks min cut for substring s[i:].
    dp = [None] * len(s)

    def _dfs(i):
      if i >= len(s):
        return 0
      min_cut = dp[i]
      if min_cut is not None:
        return min_cut

      min_cut = math.inf
      for end_id in id_to_end_ids.get(i, []):
        if end_id == len(s) - 1:
          min_cut = 0
        else:
          min_cut = min(min_cut, _dfs(end_id+1) + 1)
      dp[i] = min_cut
      return min_cut

    return _dfs(0)
115244