-
Notifications
You must be signed in to change notification settings - Fork 43
/
remove-k-digits.py
44 lines (42 loc) · 1.02 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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# V0
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/81034522
# IDEA : STACK
class Solution(object):
def removeKdigits(self, num, k):
"""
:type num: str
:type k: int
:rtype: str
"""
if len(num) == k:
return '0'
stack = []
for n in num:
while stack and k and int(stack[-1]) > int(n):
stack.pop()
k -= 1
stack.append(n)
while k:
stack.pop()
k -= 1
if not stack:
return '0'
return str(int("".join(stack)))
# V2
# Time: O(n)
# Space: O(n)
class Solution(object):
def removeKdigits(self, num, k):
"""
:type num: str
:type k: int
:rtype: str
"""
result = []
for d in num:
while k and result and result[-1] > d:
result.pop()
k -= 1
result.append(d)
return ''.join(result).lstrip('0')[:-k or None] or '0'