zoukankan      html  css  js  c++  java
  • leetcode_316. 去除重复字母

    给你一个字符串 s ,请你去除字符串中重复的字母,使得每个字母只出现一次。需保证 返回结果的字典序最小(要求不能打乱其他字符的相对位置)。
    
    注意:该题与 1081 https://leetcode-cn.com/problems/smallest-subsequence-of-distinct-characters 相同
    
     
    
    示例 1:
    
    输入:s = "bcabc"
    输出:"abc"
    示例 2:
    
    输入:s = "cbacdcbc"
    输出:"acdb"
     
    
    提示:
    
    1 <= s.length <= 104
    s 由小写英文字母组成
    
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/remove-duplicate-letters
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
    
    class Solution:
        def removeDuplicateLetters(self, s: str) -> str:
            stack=[]
            temp_set=set()#字符是否已经存在
            dic={}
            for i in range(len(s)):
                dic[s[i]]=i#字符最后出现位置
    
            for i, x in enumerate(s):
                if not stack :#如果stack为空
                    stack.append(x)
                    temp_set.add(x)
                if x in temp_set:#如果已经在集合中
                    continue
                while(stack and stack[-1]>x and i<dic[stack[-1]]):
                    #如果stack非空,栈顶大于x 且后面还有栈顶元素
                    t=stack.pop()
                    temp_set.remove(t)
                else:
                    stack.append(x)
                    temp_set.add(x)
            return ''.join(stack)
    
    class Solution:
        def removeDuplicateLetters(self, s: str) -> str:
            stack=[]
            temp_set=set()#字符是否已经存在
            dic={}
            for i in range(len(s)):
                dic[s[i]]=i#字符最后出现位置
    
            for i, x in enumerate(s):
                if x not in temp_set:#如果已经在集合中
                    while(stack and stack[-1]>x and i<dic[stack[-1]]):
                    #如果stack非空,栈顶大于x 且后面还有栈顶元素
                        t=stack.pop()
                        temp_set.remove(t)
                    stack.append(x)
                    temp_set.add(x)
            return ''.join(stack)
    
  • 相关阅读:
    软件开发人员的简历项目经验怎么写?
    mapreduce 多种输入
    lnmp如何实现伪静态,默认目录伪静态
    LNMP环境中WordPress程序伪静态解决方案
    wordpress必装的插件 wp最常用的十个插件
    debian系统下改语言设置
    Centos7 开启端口
    EventProcessor与WorkPool用法--可处理多消费者
    Disruptor入门
    Disruptor初级入门
  • 原文地址:https://www.cnblogs.com/hqzxwm/p/14101104.html
Copyright © 2011-2022 走看看