상세 컨텐츠

본문 제목

[LeetCode] Remove Duplicate Letters | stack | 파이썬 알고리즘 인터뷰, 정답, 소스코드

Coding Test/문제풀이

by yooputer 2023. 6. 15. 09:55

본문

박상길, 『파이썬 알고리즘 인터뷰』를 정리한 내용입니다.

https://leetcode.com/problems/remove-duplicate-letters

 

Remove Duplicate Letters - LeetCode

Can you solve this real interview question? Remove Duplicate Letters - 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 re

leetcode.com


문제 요약

  • 문자열이 주어질 때 문자열에서 중복된 문자를 제거하여 사전순으로 가장 빠른 문자열을 구하라. 

문제 조건

  • 1 <= 문자열 길이 <= 10000

핵심 전략

  • stack을 사용해 answer 저장
  • stack에 push할 char이 stack.top보다 작고 counter[stack.top] > 0이면 pop하기


소스코드

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

        for char in s:
            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)

 

관련글 더보기