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.
The length of num is less than 10002 and will be ≥ k. The given num does not contain any leading zero.
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.
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.
Input: num = "10", k = 2
Output: "0"
Explanation: Remove all the digits from the number and
it is left with nothing which is 0.
这道题是说,给定的一个字符串数字 num,从中移除 k 个数字,使得最后的数字最小。
不难发现以下的规律:
num = "132219", k = 2 # 4比3大,删除4
num = "12219", k = 1 # 3比(第一个)2大,删除3
num = "1219", k = 0 # (第二个)2比(第二个)1大,删除(第二个)2
注:此题有很多边界情况,要综合考虑各种情况。
class Solution:
def removeKdigits(self, num, k):
"""
:type num: str
:type k: int
:rtype: str
"""
lens = len(num)
if lens == 0 or lens == k:
return '0'
if k == 0:
return num
i = 0
while i < len(num) - 1 and k > 0:
if num[i] > num[i+1]:
num = num[:i] + num[i+1:]
k -= 1
if i > 0: # "110"
i -= 1
else:
i += 1
if k > 0: # 删除末尾k个数字
num = num[:len(num)-k]
while len(num) > 1 and num[0] == '0': # 删除前导0
num = num[1:]
return num
print(Solution().removeKdigits("1432219", 3)) # 1219
print(Solution().removeKdigits("10200", 1)) # 200
print(Solution().removeKdigits("10", 2)) # 0
print(Solution().removeKdigits("112", 2)) # 1
print(Solution().removeKdigits("110", 2)) # 0
print(Solution().removeKdigits("996414", 2)) # 6414
print(Solution().removeKdigits("12345", 2)) # 123
print(Solution().removeKdigits("12354", 1)) # 1234