LeetCode 题解工作台

操作后字符串的最短长度

给你一个字符串 s 。 你需要对 s 执行以下操作 任意 次: 选择一个下标 i ,满足 s[i] 左边和右边都 至少 有一个字符与它相同。 删除 i 左边 离它 最近 的 s[i] 字符。 删除 i 右边 离它 最近 的 s[i] 字符。 请你返回执行完所有操作后, s 的 最短 长度。 示例 1…

category

3

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 哈希·表·结合·string

bolt

答案摘要

我们可以统计字符串中每个字符出现的次数,然后遍历计数数组,如果字符出现的次数为奇数,则最后该字符剩余 个,如果字符出现的次数为偶数,则最后该字符剩余 个。我们可以将所有字符的剩余个数相加,即为最终字符串的长度。 时间复杂度 ,其中 为字符串 的长度。空间复杂度 ,其中 为字符集的大小,本题中 $|\Sigma| = 26$。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 s 。

你需要对 s 执行以下操作 任意 次:

  • 选择一个下标 i ,满足 s[i] 左边和右边都 至少 有一个字符与它相同。
  • 删除 i 左边 离它 最近 的 s[i] 字符。
  • 删除 i 右边 离它 最近 的 s[i] 字符。

请你返回执行完所有操作后, s 的 最短 长度。

 

示例 1:

输入:s = "abaacbcbb"

输出:5

解释:
我们执行以下操作:

  • 选择下标 2 ,然后删除下标 0 和 3 处的字符,得到 s = "bacbcbb" 。
  • 选择下标 3 ,然后删除下标 0 和 5 处的字符,得到 s = "acbcb" 。

示例 2:

输入:s = "aa"

输出:2

解释:
无法对字符串进行任何操作,所以返回初始字符串的长度。

 

提示:

  • 1 <= s.length <= 2 * 105
  • s 只包含小写英文字母。
lightbulb

解题思路

方法一:计数

我们可以统计字符串中每个字符出现的次数,然后遍历计数数组,如果字符出现的次数为奇数,则最后该字符剩余 11 个,如果字符出现的次数为偶数,则最后该字符剩余 22 个。我们可以将所有字符的剩余个数相加,即为最终字符串的长度。

时间复杂度 O(n)O(n),其中 nn 为字符串 ss 的长度。空间复杂度 O(Σ)O(|\Sigma|),其中 Σ|\Sigma| 为字符集的大小,本题中 Σ=26|\Sigma| = 26

1
2
3
4
5
class Solution:
    def minimumLength(self, s: str) -> int:
        cnt = Counter(s)
        return sum(1 if x & 1 else 2 for x in cnt.values())
speed

复杂度分析

指标
时间O(n)
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Can the candidate quickly implement a solution using a hash table to count frequencies?

  • question_mark

    Does the candidate consider all edge cases like an already minimal string or no removable pairs?

  • question_mark

    Is the candidate aware of the importance of focusing only on character frequencies for an optimized solution?

warning

常见陷阱

外企场景
  • error

    Ignoring edge cases where no adjacent pairs exist and not optimizing for a direct frequency-based solution.

  • error

    Incorrectly handling cases with an odd number of identical characters that can’t fully form pairs.

  • error

    Overcomplicating the solution by attempting to manually remove pairs instead of focusing on character frequencies.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What happens if the string is composed entirely of unique characters?

  • arrow_right_alt

    Can this problem be solved using a stack approach instead of hash tables?

  • arrow_right_alt

    How does the time complexity change when considering strings of varying lengths or different characters?

help

常见问题

外企场景

操作后字符串的最短长度题解:哈希·表·结合·string | LeetCode #3223 中等