Stack: LeetCode 316 remove duplicate letters

class Solution:
def removeDuplicateLetters(self, s: str) -> str:
last_occur = {ch:i for i, ch in enumerate(s)}
stack = ["!"]
visited = set()
for i, ch in enumerate(s):
if ch in visited:continue
while ch < stack[-1] and last_occur[stack[-1]] > i:
visited.remove(stack.pop())
stack.append(ch)
visited.add(ch)
return "".join(stack[1:])

Data Scientist/MLE/SWE @takemobi