[LeetCode]316. Remove Duplicate Letters
316. Remove Duplicate Letters
暴力
import collections
class Solution(object):
def removeDuplicateLetters(self, s):
"""
:type s: str
:rtype: str
"""
res = ''
for _ in set(s):
top, idx = s[0], 0
counter = collections.Counter(s)
# 找到top
for j in range(len(s)):
if s[j] < top:
top, idx = s[j], j
if counter[s[j]] == 1:
break
counter[s[j]] -= 1
res += top
# 删除最小字符之前的子串
s = s[idx+1:].replace(top, '')
return res
栈
class Solution(object):
def removeDuplicateLetters(self, s):
"""
:type s: str
:rtype: str
"""
counter = collections.Counter(s)
stack = list() # 保持递增顺序
for c in s:
counter[c] -= 1
if c in stack:
continue
while stack and stack[-1] > c and counter[stack[-1]]:
stack.pop()
stack.append(c)
return ''.join(stack)

关注公众号:数据结构与算法那些事儿,每天一篇数据结构与算法