leetcode 316. Remove Duplicate Letters

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 1:

Input: "bcabc"
Output: "abc"

Example 2:

Input: "cbacdcbc"
Output: "acdb"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
def removeDuplicateLetters(self, s):
"""
:type s: str
:rtype: str
"""
res = [0]*26
pos = 0#the smallest s[i]
for i in range(len(s)):
tmp = ord(s[i])-97
res[tmp] += 1
for i in range(len(s)):
if s[pos] > s[i]:pos = i
res[ord(s[i])-97] -= 1
if res[ord(s[i])-97] == 0:
break
return '' if len(s) == 0 else s[pos] + self.removeDuplicateLetters(s[pos+1:].replace(s[pos],''))

a clear solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
def removeDuplicateLetters(self, s):
"""
:type s: str
:rtype: str
"""
rindex = {c: i for i, c in enumerate(s)}
result = ''
for i, c in enumerate(s):
if c not in result:
while c < result[-1:] and i < rindex[result[-1]]:
result = result[:-1]
result += c
return result