I have implemented two methods:
1. The brute force method.
First, consider one input and only delete 1 number to minimize the result.
Then, for an input num and k, we perform the above operations on num k times, then
class Solution:
def removeKdigits(self, num: str, k: int) -> str:
length = len(num)
num_val = int(num)
if num_val == 0 or length <= k:
return "0"
num_list = []
for letter in num:
num_list.append(int(letter))
print(num_list)
#num_list
start_index = 0
for i in range(k):#执行k次
length = len(num_list)
for j in range(length-1):
if num_list[j] > num_list[j+1]:
num_list.pop(j)
break
if j == length - 2 and num_list[j] <= num_list[j+1]:
num_list.pop(-1)
start_index
newlist = num_list
finallength = len(newlist)
if list(set(newlist)) == [0]:
return "0"
index = 0
while newlist[index] == 0:
index += 1
res = ''
for value in newlist[index:]:
res += str(value)
return res
2. Stack operation based on greedy algorithm
We first build a stack to store the reserved numbers.
Calculate index = len (array)-k
Iterate over each number in the array:
For the first number, put it on the stack first
For each subsequent:
If the number to be deleted k == 0:
append the following numbers in the array to the stack
If the number to be deleted k> 0 and the number being traversed by the array <stack top:
while k> 0 and stack non-empty and stack top> this number:
stack top pop
k-= 1 After
jumping out of the loop, the
stack .append (this number)
If the number to be deleted k> 0 and the number that the array is traversing> = stack top:
stack.append (this number)
After jumping out of the traversal,
if k> 0:
only take the front of the stack [: index]
If there is only 0 in the stack:
return str (0)
If the stack [0] == 0
gets the first number not equal to 0, from it to the stack [-1], returns a str
class Solution:
def removeKdigits(self, num: str, k: int) -> str:
length = len(num)
num_val = int(num)
#oldk = k
if num_val == 0 or length <= k:
return "0"
num_list = []
for letter in num:
num_list.append(int(letter))
print(num_list)
should = length - k
#num_list
zhan = []
#zhan#.append(num_list[0])
tempindex = 0
shanwan = False
for i in range(length):
if k == 0:
for value in num_list[i:]:
zhan.append(value)#shanwan = True
break
elif zhan == []:
zhan.append(num_list[i])
else:
if zhan[-1] <= num_list[i]:
zhan.append(num_list[i])
elif zhan[-1] > num_list[i]:
while k > 0 and zhan != [] and zhan[-1] > num_list[i]:
zhan.pop(-1)
k -= 1
zhan.append(num_list[i])
if k > 0:
zhan = zhan[:should ]
print(zhan)
#while len(zhan) < should:
# zhan.append(num_list[tempindex + 1])
# tempindex += 1
if list(set(zhan)) == [0]:#0
return '0'
while zhan[0] == 0:
zhan.pop(0)
res = ''
for value in zhan:
res += str(value)
return res