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.git
Note:
The length of num is less than 10002 and will be ≥ k.
The given num does not contain any leading zero.github
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:app
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:less
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 位数字,使得剩下的数字最小。ui
注意:code
num 的长度小于 10002 且 ≥ k。
num 不会包含任何前导零。orm
示例 1 :three
输入: num = "1432219", k = 3 输出: "1219" 解释: 移除掉三个数字 4, 3, 和 2 造成一个新的最小的数字 1219。
示例 2 :ip
输入: num = "10200", k = 1 输出: "200" 解释: 移掉首位的 1 剩下的数字为 200. 注意输出不能有任何前导零。
示例 3 :
输入: num = "10", k = 2 输出: "0" 解释: 从原数字移除全部的数字,剩余为空就是0。
来源:力扣(LeetCode)
连接:https://leetcode-cn.com/probl...
著做权归领扣网络全部。商业转载请联系官方受权,非商业转载请注明出处。
# -*- coding: utf-8 -*- # @Author: 何睿 # @Create Date: 2019-09-07 07:59:40 # @Last Modified by: 何睿 # @Last Modified time: 2019-09-07 09:10:06 class Solution: def removeKdigits(self, num: str, k: int) -> str: cnt, stack = 0, [] for n in num: while cnt < k and stack and n < stack[-1]: cnt += 1 stack.pop() if n == "0" and not stack: continue stack.append(n) return "".join(stack[0:len(stack) - (k - cnt)]) or "0"