<p>There is a strange printer with the following two special properties:</p>

<ul>
	<li>The printer can only print a sequence of <strong>the same character</strong> each time.</li>
	<li>At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters.</li>
</ul>

<p>Given a string <code>s</code>, return <em>the minimum number of turns the printer needed to print it</em>.</p>

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

<pre>
<strong>Input:</strong> s = &quot;aaabbb&quot;
<strong>Output:</strong> 2
<strong>Explanation:</strong> Print &quot;aaa&quot; first and then print &quot;bbb&quot;.
</pre>

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

<pre>
<strong>Input:</strong> s = &quot;aba&quot;
<strong>Output:</strong> 2
<strong>Explanation:</strong> Print &quot;aaa&quot; first and then print &quot;b&quot; from the second place of the string, which will cover the existing character &#39;a&#39;.
</pre>

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

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

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    static int strangePrinter(string s) {
        int n = s.length();
        vector<int> prevs(n, -1);
        std::array<int, 26> char_prev;
        char_prev.fill(-1);
        for (int i = 0; i < n; i++) {
            int key = s[i] - 'a';
            prevs[i] = char_prev[key];
            char_prev[key] = i;
        }

        std::vector<std::vector<int>> min_turns(100, std::vector<int>(100, 0));
        min_turns[0][0] = 1;
        for (int end = 1; end < n; end++) {
            min_turns[end][end] = 1;
            for (int start = end - 1; start >= 0; start--) {
                if (prevs[end] == end - 1) {
                    min_turns[start][end] = min_turns[start][end - 1];
                } else if (prevs[end] < start) {
                    min_turns[start][end] = min_turns[start][end - 1] + 1;
                } else {
                    min_turns[start][end] = min_turns[start][end - 1] + 1;
                    int prev = prevs[end];
                    while (prev >= start) {
                        min_turns[start][end] = min(min_turns[start][end],
                                                    min_turns[start][prev] + min_turns[prev + 1][end - 1]);
                        prev = prevs[prev];
                    }
                }
            }
        }
        return min_turns[0][n - 1];
    }
};
20377