python leetcode 402. Remove K Digits

dfs或者用栈比大小 估计用dfs会超时 最后注意要去除字符串开头的0

class Solution(object):
    def removeKdigits(self, num, k):
        """
        :type num: str
        :type k: int
        :rtype: str
        """
        stack=[]
        ln=len(num)
        if k>=ln: return '0' 
        for c in num:
            while stack and k and stack[-1]>c:
                k-=1
                stack.pop()
            stack.append(c)
        while k:
            stack.pop()
            k-=1 
        return str(int(''.join(stack)))

猜你喜欢

转载自blog.csdn.net/Neekity/article/details/84613792