给你一个字符串 s
,请你去除字符串中重复的字母,使得每个字母只出现一次。需保证 返回结果的字典序最小(要求不能打乱其他字符的相对位置)。
利用单调栈实现。
有关键点,如果一个字母已经在栈中出现了,那么该字母就不应该和栈顶元素比较了。
记录每个元素剩余个数。
from collections import defaultdict
class Solution:
def removeDuplicateLetters(self, s: str) -> str:
cnts = defaultdict(lambda: 0)
for c in s:
cnts[c] += 1
stack = []
set1 = set()
for c in s:
if c not in set1:
while stack and ord(stack[-1]) >= ord(c) and cnts[stack[-1]] >= 1:
set1.remove(stack[-1])
stack.pop()
stack.append(c)
set1.add(c)
cnts[c] -= 1
else:
cnts[c] -= 1
return ''.join(stack)