LeetCode 题解工作台

移除字符串中的尾随零

给你一个用字符串表示的正整数 num ,请你以字符串形式返回不含尾随零的整数 num 。 示例 1: 输入: num = "51230100" 输出: "512301" 解释: 整数 "51230100" 有 2 个尾随零,移除并返回整数 "512301" 。 示例 2: 输入: num = "12…

category

1

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · String-driven solution strategy

bolt

答案摘要

我们可以从后往前遍历字符串,遇到第一个不是 `0` 的字符时停止遍历,然后返回从头开始到这个字符的子串。 时间复杂度 ,其中 是字符串的长度。忽略答案字符串的空间消耗,空间复杂度 。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个用字符串表示的正整数 num ,请你以字符串形式返回不含尾随零的整数 num

 

示例 1:

输入:num = "51230100"
输出:"512301"
解释:整数 "51230100" 有 2 个尾随零,移除并返回整数 "512301" 。

示例 2:

输入:num = "123"
输出:"123"
解释:整数 "123" 不含尾随零,返回整数 "123" 。

 

提示:

  • 1 <= num.length <= 1000
  • num 仅由数字 09 组成
  • num 不含前导零
lightbulb

解题思路

方法一:遍历

我们可以从后往前遍历字符串,遇到第一个不是 0 的字符时停止遍历,然后返回从头开始到这个字符的子串。

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

1
2
3
4
class Solution:
    def removeTrailingZeros(self, num: str) -> str:
        return num.rstrip("0")
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for the candidate’s understanding of string manipulation and edge case handling.

  • question_mark

    Evaluate how they handle the potential inefficiency of large string sizes.

  • question_mark

    Test if they can provide a clear solution for non-zero trimming using string methods.

warning

常见陷阱

外企场景
  • error

    Failing to handle edge cases where there are no trailing zeros.

  • error

    Misunderstanding the requirement for string manipulation versus integer-based solutions.

  • error

    Not considering the potential impact on performance with large strings.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Consider variations where the input string contains only zeros.

  • arrow_right_alt

    Explore edge cases where the number is a single-digit integer with no trailing zeros.

  • arrow_right_alt

    Evaluate solutions that also account for leading zeros (if applicable in different scenarios).

help

常见问题

外企场景

移除字符串中的尾随零题解:String-driven solution … | LeetCode #2710 简单