👨‍💻 738LeetCode

Remove Duplicate Letters

Question

Given a string which contains only lowercase letters, 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

Input: "bcabc"
Output: "abc"
Input: "cbacdcbc"
Output: "acdb"

Solution

class Solution:
    def removeDuplicateLetters(s):
        from collections import defaultdict
        last_index = defaultdict(int)
        for i, ch in enumerate(s):
            last_index[ch] = i
        ret = ''
        for i, ch in enumerate(s):
            if ch not in ret:
                # If curr can be put before the last char
                while len(ret) and ch < ret[-1] \
                        and i < last_index[ret[-1]]:
                    ret = ret[:-1]
                ret += ch
        return ret