1. 程式人生 > >python leetcode 402. Remove K Digits

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)))