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:
Given "bcabc"
Return "abc"
Given "cbacdcbc"
Return "acdb"
Solution: Stack & HashSet
import collections
class Solution(object):
def removeDuplicateLetters(self, s):
"""
:type s: str
:rtype: str
"""
count = collections.defaultdict(int)
for char in s:
count[char] += 1
stack = []
using = set()
for char in s:
if char not in using:
while stack and char <= stack[-1] and count[stack[-1]]:
using.remove(stack.pop())
stack.append(char)
using.add(char)
count[char] -= 1
return ''.join(stack)