LEETCODE - Remove Duplicated Letters

Coaspe·2021년 7월 23일
0

Algorithm - 스택

목록 보기
1/1
post-thumbnail
from typing import List
from collections import Counter

class Solution:
    def removeDuplicateLettersRecur(self, s: str) -> str:
        for char in sorted(set(s)):
            suffix = s[s.index(char):]
            # 전체 집합과 접미사 집합이 일치할 때 분리 진행
            if set(s) == set(suffix):
                return char + self.removeDuplicateLetters(suffix.replace(char, ''))
        return ''
        
    def removeDuplicateLettersStack(self, s: str) -> str:
        counter, seen, stack = 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)
profile
https://github.com/Coaspe

0개의 댓글