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"
原文地址:leetcode Remove Duplicate Letters
更多题解可见 https://www.hrwhisper.me/leetcode-algorithm-solution/
找每个字符出现的最后的位置, 取其中最小的作为end。(这个元素必须在end或者end以前出现,否则就没了= =)
从start(一开始设为0)枚举到end,最小的那个作为当前的字符。如此循环。
如:dcbacdcd
最后出现的位置:a:3 , b: 2, c : 6, d: 7
于是0~2中最小的元素为b
接着3~3 为a
接着 4~6 为c
接着 7~7 为d
所以为bacd
class Solution(object):
def removeDuplicateLetters(self, s):
if not s: return ''
last_pos = collections.defaultdict(int)
dic = set(s)
for i, c in enumerate(s):
last_pos[c] = i
last_pos = collections.OrderedDict(sorted(last_pos.items(), key=lambda x: x[1]))
start, end = 0, last_pos.items()[0][1]
ans = []
for i in xrange(len(last_pos)):
min_c = 'z'
for k in xrange(start, end + 1):
if min_c > s[k] and s[k] in last_pos:
min_c = s[k]
start = k + 1
ans += [min_c]
del last_pos[min_c]
if not last_pos: break
end = last_pos.items()[0][1]
return ''.join(ans)
本文由 hrwhisper 原创发布,转载请点名出处