https://leetcode.cn/problems/remove-duplicate-letters/
给你一个字符串 s ,请你去除字符串中重复的字母,使得每个字母只出现一次。需保证 返回结果的字典序最小(要求不能打乱其他字符的相对位置)。
示例 1:
输入:s = “bcabc”
输出:“abc”
class Solution:
def removeDuplicateLetters(self, s: str) -> str:
# 单调栈+哈希表
dic = collections.Counter(s)
stack = [] # 空栈,最后拼接栈中元素
for item in s:
dic[item] -= 1
if item in stack:
continue
while stack and stack[-1] > item and dic[stack[-1]] > 0:
# 当该数在后面没有重复的数字时,就不能再出栈了。
stack.pop()
stack.append(item)
return ''.join(stack)