Short Python using stack


  • 0

    Pop out the last element in stack whenever it is lexicographical bigger than current char c and it is still available in count.

    class Solution(object):
        def removeDuplicateLetters(self, s):
            """
            :type s: str
            :rtype: str
            """
            count = collections.Counter(s)
            seen, stack = set(), []
            for c in s:
                count[c] -= 1
                if c not in seen:
                    while stack and stack[-1] > c and count[stack[-1]]:
                        seen.remove(stack.pop())
                    stack.append(c)
                    seen.add(c)
            return "".join(stack)
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.