LeetCode 题解工作台

删除字符使字符串变好

一个字符串如果没有 三个连续 相同字符,那么它就是一个 好字符串 。 给你一个字符串 s ,请你从 s 删除 最少 的字符,使它变成一个 好字符串 。 请你返回删除后的字符串。题目数据保证答案总是 唯一的 。 示例 1: 输入: s = "le e etcode" 输出: "leetcode" 解释…

category

1

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · String-driven solution strategy

bolt

答案摘要

我们可以遍历字符串 ,并使用一个数组 记录当前的答案。对于每一个字符 ,如果 $i \lt 2$ 或者 与 $s[i - 1]$ 不等,或者 与 $s[i - 2]$ 不等,我们就将 添加到 中。 最后,我们将 中的字符连接起来,就得到了答案。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

一个字符串如果没有 三个连续 相同字符,那么它就是一个 好字符串 。

给你一个字符串 s ,请你从 s 删除 最少 的字符,使它变成一个 好字符串

请你返回删除后的字符串。题目数据保证答案总是 唯一的

 

示例 1:

输入:s = "leeetcode"
输出:"leetcode"
解释:
从第一组 'e' 里面删除一个 'e' ,得到 "leetcode" 。
没有连续三个相同字符,所以返回 "leetcode" 。

示例 2:

输入:s = "aaabaaaa"
输出:"aabaa"
解释:
从第一组 'a' 里面删除一个 'a' ,得到 "aabaaaa" 。
从第二组 'a' 里面删除两个 'a' ,得到 "aabaa" 。
没有连续三个相同字符,所以返回 "aabaa" 。

示例 3:

输入:s = "aab"
输出:"aab"
解释:没有连续三个相同字符,所以返回 "aab" 。

 

提示:

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

解题思路

方法一:模拟

我们可以遍历字符串 ss,并使用一个数组 ans\textit{ans} 记录当前的答案。对于每一个字符 s[i]\textit{s[i]},如果 i<2i \lt 2 或者 s[i]s[i]s[i1]s[i - 1] 不等,或者 s[i]s[i]s[i2]s[i - 2] 不等,我们就将 s[i]s[i] 添加到 ans\textit{ans} 中。

最后,我们将 ans\textit{ans} 中的字符连接起来,就得到了答案。

时间复杂度 O(n)O(n),其中 nn 为字符串 ss 的长度。忽略答案的空间消耗,空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
class Solution:
    def makeFancyString(self, s: str) -> str:
        ans = []
        for i, c in enumerate(s):
            if i < 2 or c != s[i - 1] or c != s[i - 2]:
                ans.append(c)
        return "".join(ans)
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    Candidate demonstrates a clear understanding of how to traverse the string efficiently.

  • question_mark

    Candidate handles edge cases correctly, ensuring no deletions when unnecessary.

  • question_mark

    Candidate focuses on the O(n) time complexity and avoids unnecessary space usage.

warning

常见陷阱

外企场景
  • error

    Forgetting to handle edge cases like strings with no triplets.

  • error

    Not considering the in-place deletion, leading to unnecessary space usage.

  • error

    Improperly handling the first and last characters, which may not be part of a triplet.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Extend the problem to handle uppercase letters as well.

  • arrow_right_alt

    Alter the problem to allow a configurable number of consecutive characters.

  • arrow_right_alt

    Change the problem to return the number of deletions instead of the final string.

help

常见问题

外企场景

删除字符使字符串变好题解:String-driven solution … | LeetCode #1957 简单