LeetCode 题解工作台

最小化字符串长度

给你一个下标从 0 开始的字符串 s ,重复执行下述操作 任意 次: 在字符串中选出一个下标 i ,并使 c 为字符串下标 i 处的字符。并在 i 左侧 (如果有)和 右侧 (如果有)各 删除 一个距离 i 最近 的字符 c 。 请你通过执行上述操作任意次,使 s 的长度 最小化 。 返回一个表示 …

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 哈希·表·结合·string

bolt

答案摘要

题目实际上可以转化为求字符串中不同字符的个数,因此,我们只需要统计字符串中不同字符的个数即可。 时间复杂度 ,其中 是字符串 的长度。空间复杂度 ,其中 是字符集,这里是小写英文字母,因此 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个下标从 0 开始的字符串 s ,重复执行下述操作 任意 次:

  • 在字符串中选出一个下标 i ,并使 c 为字符串下标 i 处的字符。并在 i 左侧(如果有)和 右侧(如果有)各 删除 一个距离 i 最近 的字符 c

请你通过执行上述操作任意次,使 s 的长度 最小化

返回一个表示 最小化 字符串的长度的整数。

 

示例 1:

输入:s = "aaabc"
输出:3
解释:在这个示例中,s 等于 "aaabc" 。我们可以选择位于下标 1 处的字符 'a' 开始。接着删除下标 1 左侧最近的那个 'a'(位于下标 0)以及下标 1 右侧最近的那个 'a'(位于下标 2)。执行操作后,字符串变为 "abc" 。继续对字符串执行任何操作都不会改变其长度。因此,最小化字符串的长度是 3 。

示例 2:

输入:s = "cbbd"
输出:3
解释:我们可以选择位于下标 1 处的字符 'b' 开始。下标 1 左侧不存在字符 'b' ,但右侧存在一个字符 'b'(位于下标 2),所以会删除位于下标 2 的字符 'b' 。执行操作后,字符串变为 "cbd" 。继续对字符串执行任何操作都不会改变其长度。因此,最小化字符串的长度是 3 。

示例 3:

输入:s = "dddaaa"
输出:2
解释:我们可以选择位于下标 1 处的字符 'd' 开始。接着删除下标 1 左侧最近的那个 'd'(位于下标 0)以及下标 1 右侧最近的那个 'd'(位于下标 2)。执行操作后,字符串变为 "daaa" 。继续对新字符串执行操作,可以选择位于下标 2 的字符 'a' 。接着删除下标 2 左侧最近的那个 'a'(位于下标 1)以及下标 2 右侧最近的那个 'a'(位于下标 3)。执行操作后,字符串变为 "da" 。继续对字符串执行任何操作都不会改变其长度。因此,最小化字符串的长度是 2 。

 

提示:

  • 1 <= s.length <= 100
  • s 仅由小写英文字母组成
lightbulb

解题思路

方法一:哈希表

题目实际上可以转化为求字符串中不同字符的个数,因此,我们只需要统计字符串中不同字符的个数即可。

时间复杂度 O(n)O(n),其中 nn 是字符串 s\textit{s} 的长度。空间复杂度 O(Σ)O(|\Sigma|),其中 Σ\Sigma 是字符集,这里是小写英文字母,因此 Σ=26|\Sigma|=26

1
2
3
4
class Solution:
    def minimizedStringLength(self, s: str) -> int:
        return len(set(s))
speed

复杂度分析

指标
时间complexity is O(n) since each character is processed once. Space complexity is O(1) with a fixed 26-letter array or O(k) for a hash set storing k unique letters.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Focus on identifying unique characters efficiently.

  • question_mark

    Expect a simple hash table or set-based solution for string reduction.

  • question_mark

    Watch for off-by-one errors when counting duplicates.

warning

常见陷阱

外企场景
  • error

    Trying to remove duplicates manually with nested loops, leading to O(n^2) time.

  • error

    Forgetting that only the count of unique characters matters, not their order.

  • error

    Using extra memory unnecessarily instead of a fixed-size array or set.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Minimize string length for uppercase letters using a similar hash table approach.

  • arrow_right_alt

    Return the minimized string itself instead of just the length.

  • arrow_right_alt

    Count unique characters after allowing limited repeated removals or restricted operations.

help

常见问题

外企场景

最小化字符串长度题解:哈希·表·结合·string | LeetCode #2716 简单