본문 바로가기

자료구조와 알고리즘

316. Remove Duplicate Letters(중복 문자 제거)

class Solution:
    def removeDuplicateLetters(self, s: str) -> str:
        
        counter, seen, stack = collections.Counter(s), set(), []

        for char in s:
            counter[char] -= 1
            if char in seen:
                continue
            while stack and char < stack[-1] and counter[stack[-1]] > 0:
                seen.remove(stack.pop())
            
            stack.append(char)
            seen.add(char)
        
        return "".join(stack)