comments | difficulty | edit_url | tags | ||
---|---|---|---|---|---|
true |
困难 |
|
有台奇怪的打印机有以下两个特殊要求:
- 打印机每次只能打印由 同一个字符 组成的序列。
- 每次可以在从起始到结束的任意位置打印新字符,并且会覆盖掉原来已有的字符。
给你一个字符串 s
,你的任务是计算这个打印机打印它需要的最少打印次数。
示例 1:
输入:s = "aaabbb" 输出:2 解释:首先打印 "aaa" 然后打印 "bbb"。
示例 2:
输入:s = "aba" 输出:2 解释:首先打印 "aaa" 然后在第二个位置打印 "b" 覆盖掉原来的字符 'a'。
提示:
1 <= s.length <= 100
s
由小写英文字母组成
我们定义
考虑
在枚举时,我们可以从大到小枚举
时间复杂度
class Solution:
def strangePrinter(self, s: str) -> int:
n = len(s)
f = [[inf] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
f[i][i] = 1
for j in range(i + 1, n):
if s[i] == s[j]:
f[i][j] = f[i][j - 1]
else:
for k in range(i, j):
f[i][j] = min(f[i][j], f[i][k] + f[k + 1][j])
return f[0][-1]
class Solution {
public int strangePrinter(String s) {
final int inf = 1 << 30;
int n = s.length();
int[][] f = new int[n][n];
for (var g : f) {
Arrays.fill(g, inf);
}
for (int i = n - 1; i >= 0; --i) {
f[i][i] = 1;
for (int j = i + 1; j < n; ++j) {
if (s.charAt(i) == s.charAt(j)) {
f[i][j] = f[i][j - 1];
} else {
for (int k = i; k < j; ++k) {
f[i][j] = Math.min(f[i][j], f[i][k] + f[k + 1][j]);
}
}
}
}
return f[0][n - 1];
}
}
class Solution {
public:
int strangePrinter(string s) {
int n = s.size();
int f[n][n];
memset(f, 0x3f, sizeof(f));
for (int i = n - 1; ~i; --i) {
f[i][i] = 1;
for (int j = i + 1; j < n; ++j) {
if (s[i] == s[j]) {
f[i][j] = f[i][j - 1];
} else {
for (int k = i; k < j; ++k) {
f[i][j] = min(f[i][j], f[i][k] + f[k + 1][j]);
}
}
}
}
return f[0][n - 1];
}
};
func strangePrinter(s string) int {
n := len(s)
f := make([][]int, n)
for i := range f {
f[i] = make([]int, n)
for j := range f[i] {
f[i][j] = 1 << 30
}
}
for i := n - 1; i >= 0; i-- {
f[i][i] = 1
for j := i + 1; j < n; j++ {
if s[i] == s[j] {
f[i][j] = f[i][j-1]
} else {
for k := i; k < j; k++ {
f[i][j] = min(f[i][j], f[i][k]+f[k+1][j])
}
}
}
}
return f[0][n-1]
}
function strangePrinter(s: string): number {
const n = s.length;
const f: number[][] = new Array(n).fill(0).map(() => new Array(n).fill(1 << 30));
for (let i = n - 1; i >= 0; --i) {
f[i][i] = 1;
for (let j = i + 1; j < n; ++j) {
if (s[i] === s[j]) {
f[i][j] = f[i][j - 1];
} else {
for (let k = i; k < j; ++k) {
f[i][j] = Math.min(f[i][j], f[i][k] + f[k + 1][j]);
}
}
}
}
return f[0][n - 1];
}