Easy python solution


  • 4
    Y
    class Solution(object):
        def removeKdigits(self, num, k):
            """
            :type num: str
            :type k: int
            :rtype: str
            """
            while k > 0:
                k -= 1
                i = 0
                while i < len(num)-1:
                    if num[i] > num[i+1]:
                        break
                    i += 1
                num = num[:i] + num[i+1:]
            
            if len(num) == 0:
                return "0"
            else:
                return str(int(num))
    

    find the first pair where num[i] > num[i+1], remove num[i]
    if cannot find, remove num[-1]
    done.


  • 0

    I made a similar solution at the first time. An AC but slow pattern since we can finish it in one loop instead of K.

    def removeKdigits(self, num, k):
        def shrink(num):
            for i in range(len(num) - 1):
                if num[i] > num[i + 1]:
                    return num[:i] + num[i+1:]
            return num[:-1]
        for i in range(k):
            num = shrink(num)
        return str(int(num)) if num else "0"
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.