-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path316 Remove Duplicate Letters.py
46 lines (36 loc) · 1.15 KB
/
316 Remove Duplicate Letters.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
45
46
"""
Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only
once. You must make sure your result is the smallest in lexicographical order among all possible results.
Example:
Given "bcabc"
Return "abc"
Given "cbacdcbc"
Return "acdb"
Author: Rajeev Ranjan
"""
class Solution(object):
def removeDuplicateLetters(self, s):
"""
:type s: str
:rtype: str
"""
last_pos = [-1 for _ in xrange(26)]
n = len(s)
for i in xrange(n-1, -1, -1):
if last_pos[self._idx(s[i])] == -1:
last_pos[self._idx(s[i])] = i
stk = []
stk_set = set()
for i in xrange(n):
v = s[i]
if v not in stk_set:
while stk and stk[-1] > v and last_pos[self._idx(stk[-1])] > i:
p = stk.pop()
stk_set.remove(p)
stk.append(v)
stk_set.add(v)
return "".join(stk)
def _idx(self, x):
return ord(x) - ord('a')
if __name__ == "__main__":
assert Solution().removeDuplicateLetters("cbacdcbc") == "acdb"