LeetCode 316 Remove Duplicate Letters (Python)

Posted by 小明MaxMing on October 11, 2020

题目

Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.

Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/

解题思路

贪心,结果维护在一个单调栈中,在pop时候考试一个字符串能否被删,如果不是最后一次出现才可以被删,已经出现过的字符就不加到栈中

代码

class Solution:
    def removeDuplicateLetters(self, s) -> int:
        stack = []
        seen = set()
        last = {c: i for i, c in enumerate(s)}
        for i, c in enumerate(s):
            if c not in seen:
                while stack and c < stack[-1] and i < last[stack[-1]]:
                    seen.remove(stack.pop())
                seen.add(c)
                stack.append(c)
        return ''.join(stack)

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅