-
Notifications
You must be signed in to change notification settings - Fork 118
/
Copy pathRemove K Digits.py
32 lines (26 loc) · 1.12 KB
/
Remove K Digits.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# Lets make monotonically growing stack and save the indexes of popped elements into deletes dict.
#as soon as len(delete) == k delete those indexes from the initial string and thats the answer.
#if len(delete) < k remove k-len(delete) chars from right and thats the answer
class Solution:
def removeKdigits(self, s: str, k: int) -> str:
if len(s) == k:
return '0'
stack = []
delete = {}
for i in range(len(s)):
while stack and s[i] < stack[-1][0]:
delete[stack.pop()[1]] = 1
if len(delete) == k:
break
if len(delete) == k:
return self.deleteindexes(s, delete, k)
stack.append([s[i], i])
s1 = self.deleteindexes(s, delete, k)
return str(int(s1[:len(s1)-k +len(delete)]))
def deleteindexes(self, s, delete, k):
if not delete:
return s
if len(delete) == k:
return str(int(''.join([c for ind, c in enumerate(s) if ind not in delete])))
else:
return ''.join([c for ind, c in enumerate(s) if ind not in delete])