파비의 매일매일 공부기록

2023.09.26 Today's Challenge 본문

Problem Solving/LeetCode

2023.09.26 Today's Challenge

fabichoi 2023. 9. 26. 23:45

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

 

LeetCode - The World's Leading Online Programming Learning Platform

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 = {}
        st = []
        visited = set()

        for i in range(len(s)):
            last_occ[s[i]] = i

        for i in range(len(s)):
            if s[i] not in visited:
                while (st and st[-1] > s[i] and last_occ[st[-1]] > i):
                    visited.remove(st.pop())
                st.append(s[i])
                visited.add(s[i])
        
        return ''.join(st)
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.09.28 Today's Challenge  (0) 2023.09.28
2023.09.27 Today's Challenge  (0) 2023.09.27
2023.09.25 Today's Challenge  (0) 2023.09.25
2023.09.24 Today's Challenge  (0) 2023.09.24
2023.09.23 Today's Challenge  (0) 2023.09.23
Comments