316. Remove Duplicate Letters

kukudas·2022년 3월 15일
0

Algorithm

목록 보기
19/46
import collections

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

        for char in s:
            # 지나갔으니까 -1 해줘야함
            counter[char] -= 1
            # 이미 스택에 있으면 내가 중복이니까 스택에 넣지 않고 건너 뛰어야함
            if char in stack:
                continue

            # 사전식 순서니까 새로 들어온 문자가 사전에서 앞서고 문자열뒤에 스택에 있는 문자가 있으면 중복이니까 스택에서 없애줌
            while stack and char < stack[-1] and counter[stack[-1]]> 0:
                stack.pop()
            stack.append(char)

        return ''.join(stack)

0개의 댓글