Leetcode 每日一题
题目链接: 316. 去除重复字母
难度: 中等
解题思路: 每次当前的字符是否是小于栈顶元素的,若不小于将其pop。还需要记录某个字符是否已经在栈中出现,若已经出现过则不用在进行比较。
题解:
class Solution:
def removeDuplicateLetters(self, s: str) -> str:
count = collections.Counter(s)
visit = set()
stack = list()
for ch in s:
if ch not in visit:
while len(stack) > 0 and ch < stack[-1]:
if count[stack[-1]] > 0:
visit.remove(stack[-1])
stack.pop(-1)
else:
break
visit.add(ch)
stack.append(ch)
count[ch] -= 1
return "".join(stack)