码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode——316. 去除重复字母

时间:2019-11-04 18:03:04      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:type   code   哨兵   dup   self   elf   ash   count   style   

这道题也不是我自己想出来的。。。

class Solution(object):
    def removeDuplicateLetters(self, s):
        """
        :type s: str
        :rtype: str
        """
        counts = {}
        coun=set(s)
        for c in coun:
            counts[c]=s.count(c)

        stack, stacked = [0], set()   # stack为答案,放置哨兵,stacked为stack中已有的字符
        for c in s:
            if c not in stacked:
                while c < stack[-1] and counts[stack[-1]]:  # 当栈顶在后面还有且大于当前字符时弹出
                    stacked.remove(stack.pop())
                stack.append(c)
                stacked.add(c)
            counts[c] -= 1
        return ‘‘.join(stack[1:])
执行用时 :32 ms, 在所有 python 提交中击败了62.20%的用户
内存消耗 :11.7 MB, 在所有 python 提交中击败了44.44%的用户
 
 
——2019.11.4

leetcode——316. 去除重复字母

标签:type   code   哨兵   dup   self   elf   ash   count   style   

原文地址:https://www.cnblogs.com/taoyuxin/p/11793009.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!