移除字符串中的尾随零
难度:
标签:
题目描述
Given a positive integer num
represented as a string, return the integer num
without trailing zeros as a string.
Example 1:
Input: num = "51230100" Output: "512301" Explanation: Integer "51230100" has 2 trailing zeros, we remove them and return integer "512301".
Example 2:
Input: num = "123" Output: "123" Explanation: Integer "123" has no trailing zeros, we return integer "123".
Constraints:
1 <= num.length <= 1000
num
consists of only digits.num
doesn't have any leading zeros.
代码结果
运行时间: 26 ms, 内存: 16.3 MB
/*
* 题目思路:
* 使用Java Stream来处理字符串,虽然stream主要用于处理集合,但我们可以利用其处理字符串的功能,
* 通过reverse字符串,然后跳过开头的零,最后再reverse回来,得到去掉尾随零的字符串。
*/
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Solution {
public String removeTrailingZeros(String num) {
// 反转字符串并转换为Stream
String reversed = new StringBuilder(num).reverse().toString();
// 去掉开头的零,然后再反转回来
String result = IntStream.range(0, reversed.length())
.mapToObj(reversed::charAt)
.dropWhile(ch -> ch == '0')
.map(String::valueOf)
.collect(Collectors.joining());
return new StringBuilder(result).reverse().toString();
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.removeTrailingZeros("51230100")); // 输出: "512301"
System.out.println(sol.removeTrailingZeros("123")); // 输出: "123"
}
}
解释
方法:
该题解的基本思路是首先将输入的数字字符串进行反转,这样尾随的零就变成了字符串的开头。然后通过遍历反转后的字符串来统计连续的零的数量。遍历过程中,一旦遇到一个非零字符,就停止计数。最后,原始字符串的尾部零的数量就是反转字符串开头的零的数量。使用这个计数来从原始字符串中切除相应数量的字符,从而去除尾随零。
时间复杂度:
O(n)
空间复杂度:
O(n)
代码细节讲解
🦆
为什么选择反转字符串而不是直接从原字符串的末尾开始遍历来计数尾随零?
▷🦆
在遍历过程中,如果整个字符串都是零,例如'0000',那么算法的输出会是什么?
▷🦆
如果输入的字符串是非常长的,这种反转字符串的方法是否会有性能上的影响?
▷