LeetCode 题解工作台

清除数字

给你一个字符串 s 。 你的任务是重复以下操作删除 所有 数字字符: 删除 第一个数字字符 以及它左边 最近 的 非数字 字符。 请你返回删除所有数字字符以后剩下的字符串。 注意 ,该操作不能对左侧没有任何非数字字符的数字执行。 示例 1: 输入: s = "abc" 输出: "abc" 解释: 字…

category

3

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 栈·状态

bolt

答案摘要

我们用一个栈 `stk` 来模拟这个过程,遍历字符串 `s`,如果当前字符是数字,就弹出栈顶元素,否则将当前字符入栈。 最后将栈中的元素拼接成字符串返回。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 栈·状态 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 s 。

你的任务是重复以下操作删除 所有 数字字符:

  • 删除 第一个数字字符 以及它左边 最近 的 非数字 字符。

请你返回删除所有数字字符以后剩下的字符串。

注意,该操作不能对左侧没有任何非数字字符的数字执行。

示例 1:

输入:s = "abc"

输出:"abc"

解释:

字符串中没有数字。

示例 2:

输入:s = "cb34"

输出:""

解释:

一开始,我们对 s[2] 执行操作,s 变为 "c4" 。

然后对 s[1] 执行操作,s 变为 "" 。

 

提示:

  • 1 <= s.length <= 100
  • s 只包含小写英文字母和数字字符。
  • 输入保证所有数字都可以按以上操作被删除。
lightbulb

解题思路

方法一:栈 + 模拟

我们用一个栈 stk 来模拟这个过程,遍历字符串 s,如果当前字符是数字,就弹出栈顶元素,否则将当前字符入栈。

最后将栈中的元素拼接成字符串返回。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为字符串 s 的长度。

1
2
3
4
5
6
7
8
9
10
class Solution:
    def clearDigits(self, s: str) -> str:
        stk = []
        for c in s:
            if c.isdigit():
                stk.pop()
            else:
                stk.append(c)
        return "".join(stk)
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    Candidate can effectively apply stack-based state management to solve the problem.

  • question_mark

    Candidate is familiar with processing strings efficiently from left to right.

  • question_mark

    Candidate can relate the stack operations to real-world scenarios or other algorithms.

warning

常见陷阱

外企场景
  • error

    Forgetting to mark digits that should be removed or removing too many characters.

  • error

    Not handling edge cases like no digits in the string or consecutive digits.

  • error

    Misunderstanding the operation to apply on digits and non-digits in the string.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Consider strings with more complex patterns or large numbers of consecutive digits.

  • arrow_right_alt

    Change the constraints by allowing uppercase letters or symbols in the string.

  • arrow_right_alt

    Optimize for different input sizes or test for time efficiency in edge cases.

help

常见问题

外企场景

清除数字题解:栈·状态 | LeetCode #3174 简单