316. 去除重复字母(单调栈)

 

难度中等

给你一个字符串 s ,请你去除字符串中重复的字母,使得每个字母只出现一次。需保证 返回结果的字典序最小(要求不能打乱其他字符的相对位置)。

 

示例 1:

s = "bcabc""abc"

示例 2:

s = "cbacdcbc"
"acdb"

 

复制代码
class Solution:
    def removeDuplicateLetters(self, s: str) -> str:
        left = Counter(s)  # 统计每个字母的出现次数
        ans = []
        in_ans = set()
        for c in s:
            left[c] -= 1
            if c in in_ans:  # ans 中不能有重复字母
                continue
            # (设 x=ans[-1]) 如果 c < x,且右边还有 x,那么可以把 x 去掉,
            # 因为后面可以重新把 x 加到 ans 中
            while ans and c < ans[-1] and left[ans[-1]]:
                in_ans.remove(ans.pop())  # 标记 x 不在 ans 中
            ans.append(c)  # 把 c 加到 ans 的末尾
            in_ans.add(c)  # 标记 c 在 ans 中
        return ''.join(ans)
复制代码

 

 

复制代码
class Solution:
    def removeDuplicateLetters(self, s: str) -> str:
        s_map = {}
        for i in s:
            if i in s_map:
                s_map[i]+=1
            else:
                s_map[i] =1

        stk = []
        for ch in s:
            if ch not in stk:
                while stk and s_map[stk[-1]]>0 and ch < stk[-1]:
                    stk.pop()
                stk.append(ch)
            s_map[ch]-=1
        return "".join(stk)
复制代码

 

posted @   乐乐章  阅读(29)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
历史上的今天:
2018-04-28 结巴并行分词
点击右上角即可分享
微信分享提示