Day13-Remove K Digits(Medium)
问题描述:
Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible.
Note:
The length of num is less than 10002 and will be ≥ k.
The given num does not contain any leading zero.
从字符串中移除指定数量的数字,使剩下的字符串表示的整数型数据最小。留下的数据不能以0开头。
Example:
Example 1:
Input: num = “1432219”, k = 3
Output: “1219”
Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.
Example 2:
Input: num = “10200”, k = 1
Output: “200”
Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.
Example 3:
Input: num = “10”, k = 2
Output: “0”
Explanation: Remove all the digits from the number and it is left with nothing which is 0.
解法:
medium难度的题对我来说还是有点吃力啊,这道题是看了一位大神的博客才写出来的。我会在文末贴上这位大神的博客地址。看完答案后还是挺简单的。就是用一个栈结构来存储数据,我们遍历num中的字符,如果当前字符比栈顶的字符小,并且k值大于0,那我们就推出栈顶元素,同时k - 1(这个过程在一个循环里),如果栈不为空或者当前元素不为‘0’的时候我们向栈中添加当前元素(这一步想不明白的同学可以想一想如果栈为空且当前元素为‘0’我们向栈中加入‘0’这样领头位置就是0了,不满足题目要求啊,所以我们要设置一个if条件排除这种情况)。如果遍历完,k还是大于0,那说明前面几位的值都已经是该位置的最小元素了,我们移除后面的k位就可以了。
由于减少空间复杂度,我们可以不用设置额外的数组表示栈空间,我们用字符也是可以的。
class Solution:
def removeKdigits(self, num: str, k: int) -> str:
result = ''
for n in num:
while result and int(result[-1]) > int(n) and k:
k -= 1
result = result[:-1]
if result or n != '0':
result += n
while k:
result = result[:-1]
k -= 1
if result:
return result
else:
return '0'