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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
from collections import Counter
def removeDuplicateLetters(s):
counter = Counter(s)
stack = []
# print(counter)
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)
# print(stack)
return ''.join(stack)
s = "cbacdcbc"
removeDuplicateLetters(s)
|
cs |
while stack and char < stack[-1] and counter[stack[-1]] > 0:
stack.pop()
1. stack: stack 이 비어있는데 pop 하면 에러 발생
2. char < stack[-1]: 'a' < 'b' 우선순위의 문자가 와야함
3. counter[stack[-1]] >0: 더이상 없는 문자는 뺄 수 없음
pop()을 당하는 문자(stack[-1)의 조건은 char 보다 사전에서 뒤에 있고, 뒤에 다시 붙일 문자가 남아있어야 한다.
PRINT:
['c']
['b']
['a']
['a', 'c']
['a', 'c', 'd']
['a', 'c', 'd', 'b']
'알고리즘 문제풀이 with 파이썬 > LeetCode' 카테고리의 다른 글
[해시] Jewels and Stones (0) | 2021.09.18 |
---|---|
[스택] Daily Temperatures (0) | 2021.09.14 |
[스택] Valid Parentheses (0) | 2021.09.12 |
[배열] Best Time to Buy and Sell Stock (0) | 2021.09.11 |
[배열] Product of Array Except Self (0) | 2021.09.11 |