본문 바로가기
Programming/LeetCode

[LeetCode] Remove Duplicate Letters

by 데이터현 2022. 3. 29.

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

 

Remove Duplicate Letters - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

class Solution:
    def removeDuplicateLetters(self, s: str) -> str:
        last_occ = {}
        visited = set()
        stack = []
        for i in range(len(s)):
            last_occ[s[i]] = i
        for i in range(len(s)):
            if s[i] not in visited:
                while (stack and stack[-1] > s[i] and last_occ[stack[-1]] > i):
                    visited.remove(stack.pop())

                stack.append(s[i])
                visited.add(s[i])
    
        return ''.join(stack)

댓글