Remove k digits

class Solution:


def removeKdigits(self, num: str, k: int) -> str:

    if len(num) == k:#no need to search, just return 0

        return str(0)

    

    point = 0 #use the point to traverse the num

    while(k>0 and point < len(num)-1):

        if num[point] > num[point+1]: #from left to right, each time we check if the digit that is larger than the digit behind

            num = num[:point]+num[point+1:] #if so, delete that digit

            k-=1

            if point!=0:#except point equals to 0, we step back one digit

                point-=1

            continue #jump the point+=1 statement

        point+=1 


    if k == 0:#num[:-k] is not valid if k==0

        return  str(int(num))


    return str(int(num[:-k]))#if k > 0, it means the num is in ascending order, we just need drop the k digits at the rear  

Comments

Popular posts from this blog

Valid Username Regular Expression

Rotate String in Right Direction in java

Sum of Elements of Lower Triangular Matrix