LeetCode 题解工作台
移除字符串中的尾随零
给你一个用字符串表示的正整数 num ,请你以字符串形式返回不含尾随零的整数 num 。 示例 1: 输入: num = "51230100" 输出: "512301" 解释: 整数 "51230100" 有 2 个尾随零,移除并返回整数 "512301" 。 示例 2: 输入: num = "12…
1
题型
6
代码语言
3
相关题
当前训练重点
简单 · String-driven solution strategy
答案摘要
我们可以从后往前遍历字符串,遇到第一个不是 `0` 的字符时停止遍历,然后返回从头开始到这个字符的子串。 时间复杂度 ,其中 是字符串的长度。忽略答案字符串的空间消耗,空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路
题目描述
给你一个用字符串表示的正整数 num ,请你以字符串形式返回不含尾随零的整数 num 。
示例 1:
输入:num = "51230100" 输出:"512301" 解释:整数 "51230100" 有 2 个尾随零,移除并返回整数 "512301" 。
示例 2:
输入:num = "123" 输出:"123" 解释:整数 "123" 不含尾随零,返回整数 "123" 。
提示:
1 <= num.length <= 1000num仅由数字0到9组成num不含前导零
解题思路
方法一:遍历
我们可以从后往前遍历字符串,遇到第一个不是 0 的字符时停止遍历,然后返回从头开始到这个字符的子串。
时间复杂度 ,其中 是字符串的长度。忽略答案字符串的空间消耗,空间复杂度 。
class Solution:
def removeTrailingZeros(self, num: str) -> str:
return num.rstrip("0")
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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).