402. Remove K Digits[LeetCode]

402. Remove K Digits

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.

给定一个用字符串表示的非负整数num,从中移除k位数字,使得剩下的数字尽可能小。

Notion:
  • The length of num is less than 10^5 and will be ≥ k.
  • The given num does not contain any leading zero.

Example1:

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.

解题思路:

利用栈(Stack)结构,使得栈中的数字尽量保持递增的顺序

补充知识:

str.join()函数

>>>seq = ['1','2','3','4']
>>>print('.'.join(seq))
1.2.3.4
>>>print(':'.join(seq))
1:2:3:4
print(' '.join(seq))
1 2 3 4
  #去掉序列的前缀0
>>>int('001100')
1100
>>>str(int(''001100))
'1100'

代码:
class Solution(object):
    def removeKdigits(self, num, k):
        """
        :type num: str
        :type k: int
        :rtype: str
        """
        size = len(num)
        stack = ['0']    #加上一个stack['0']是因为后面stack[-1]需要一个初始值,'0'是因为比较的对象为字符型。
        
        for i in range(size):
            while stack[-1] > num[i] and len(stack) > i - k + 1: #不管怎样num[i]都要进栈,但是在此之前需要判断上一个数字是否需要出栈。
                stack.pop()      #如果要进栈的数字小于栈顶元素&&,栈顶元素出栈。
            stack.append(num[i])
            
        while len(stack) > size - k + 1:  #字符串已经为递增型,但是还有没有删除够k个字符,那就从最后开始删除大的数字。
            stack.pop()
            
        return str(int(''.join(stack)))   #int是去掉序列的前缀0,然后转换成字符型

你可能感兴趣的:(402. Remove K Digits[LeetCode])