leetcode - 316. Remove Duplicate Letters

Description

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.

Example 1:

Input: s = "bcabc"
Output: "abc"

Example 2:

Input: s = "cbacdcbc"
Output: "acdb"

Constraints:

1 <= s.length <= 10^4
s consists of lowercase English letters.

Solution

Use a map to keep track of the last time each alphabet appears, every time when pushing a new alphabet into the stack, check if the top element of the stack is larger than current element, and if the top element would appear again. If so, then pop the top element.

All elements in the stack follow the rule: either it’s smaller than the right, or it won’t appear later.

Time complexity: o ( n ) o(n) o(n)
Space complexity: o ( n ) o(n) o(n)

Code

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

你可能感兴趣的:(OJ题目记录,leetcode,linux,服务器)